What is a method in Java?
A
A variable B
A block of code that performs a task C
An array D
A data type
Analysis & Theory
A method is a block of code that performs a specific task when called.
Which keyword is used to define a method that does not return a value?
A
return B
void C
null D
static
Analysis & Theory
`void` means the method does not return a value.
How do you call a method named `printHello()`?
A
`call printHello();` B
`printHello[];` C
`printHello();` D
`method printHello();`
Analysis & Theory
To call a method, use `methodName();`
What is the output?
```java
public static void greet() {
System.out.println("Hello");
}
public static void main(String[] args) {
greet();
}```
A
Hello B
greet C
Nothing D
Error
Analysis & Theory
The `greet()` method prints "Hello" when called in `main`.
What is the return type of this method?
```java
public static int square(int x) {
return x * x;
}```
A
void B
double C
int D
String
Analysis & Theory
`int` is the return type, since the method returns an integer value.
Which of the following is the correct method signature?
A
method myFunction() B
void myFunction[] C
public static void myFunction() D
main method()
Analysis & Theory
The correct method signature includes return type, name, and parentheses: `public static void myFunction()`.
What is method overloading in Java?
A
Calling a method multiple times B
Writing multiple methods with same name but different parameters C
Using a method from another class D
Using recursion
Analysis & Theory
Method overloading allows multiple methods with the same name but different parameter lists.
What is the output?
```java
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
}```
A
5 B
23 C
Error D
a + b
Analysis & Theory
`add(2, 3)` returns 5 and it is printed by `System.out.println()`.
Which keyword allows a method to be used without creating an object?
A
final B
public C
private D
static
Analysis & Theory
The `static` keyword allows a method to be called on the class itself without creating an object.
Can a method return multiple values in Java?
A
Yes, using multiple return statements B
No, Java methods can only return one value C
Yes, using commas D
Yes, by returning two variables
Analysis & Theory
Java methods return only one value. To return multiple, use an array or object.