Java Methods Flashcards
What is a method in Java?
A method in Java is a block of code that performs a specific task and can be called to execute that task.
It typically has a name, a return type, parameters (optional), and a body.
Methods help avoid code repetition and improve readability.
What is the syntax of a method declaration in Java?
returnType methodName(parameters)
{
// Method body
}
What is method overloading in Java?
Method overloading in Java allows multiple methods with the same name but different parameter lists (number or type of parameters).
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
What is the purpose of the void keyword in a method declaration?
The void keyword indicates that the method does not return any value.
What is recursion in Java?
Recursion is when a method calls itself to solve a problem.
It typically has a base case to terminate the recursion and an recursive case where the method calls itself.
What will the following method output?
public void countdown(int n) {
if (n == 0) {
System.out.println(“Done!”);
} else {
System.out.println(n);
countdown(n - 1); // Recursive call
}
}
5
4
3
2
1
Done!
How do you pass arguments by value in Java?
In Java, arguments are passed by value, meaning a copy of the value is passed to the method. Changes to the parameters inside the method do not affect the original arguments.
How do you return multiple values from a method in Java?
Java methods can return only one value, but you can return multiple values by:
Returning an array or an object.
Using a custom class to hold multiple return values.
Eg: public int[] getCoordinates() {
return new int[]{10, 20}; // Returning an array
}
What is the difference between a static and non-static method in Java?
Static Method: Belongs to the class rather than instances of the class. It can be called without creating an object.
Non-static Method: Belongs to an object of the class and can only be called on an instance of the class.
What will the following code output, and why?
public class Main {
public static void main(String[] args) {
System.out.println(sum(5));
}
public static int sum(int n) { if (n == 1) { return 1; } else { return n + sum(n - 1); // Recursive call } } }
15
Explanation:
The method sum(5) computes 5 + 4 + 3 + 2 + 1 = 15 using recursive calls.