Practice Questions — Methods in Java
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output of the following code?
public class Test {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
System.out.println(square(5));
System.out.println(square(3) + square(4));
}
}square(5) returns 25. square(3) returns 9, square(4) returns 16. Then add them.
2525Question 2
Easy
What is the output?
static void printStars(int n) {
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println();
}
printStars(3);
printStars(5);The method prints n stars followed by a newline.
********Question 3
Easy
What is the output?
static int max(int a, int b) {
if (a > b) return a;
return b;
}
System.out.println(max(10, 20));
System.out.println(max(50, 30));
System.out.println(max(7, 7));The method returns the larger of the two values. What if they are equal?
20507Question 4
Easy
What is the output?
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("Inside: a=" + a + " b=" + b);
}
int x = 10, y = 20;
swap(x, y);
System.out.println("Outside: x=" + x + " y=" + y);Java is pass-by-value. The swap happens on copies of x and y.
Inside: a=20 b=10Outside: x=10 y=20Question 5
Medium
What is the output?
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.5));
System.out.println(add(1, 2, 3));The compiler selects the overloaded method based on the argument types and count.
56.06Question 6
Medium
What is the output?
static void modify(int[] arr) {
arr[0] = 100;
}
int[] numbers = {1, 2, 3};
modify(numbers);
System.out.println(numbers[0]);
System.out.println(numbers[1]);Arrays are objects. The method receives a copy of the reference, but it points to the same array.
1002Question 7
Medium
What is the output?
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
System.out.println(sum());
System.out.println(sum(5));
System.out.println(sum(1, 2, 3, 4));Varargs can be called with 0 or more arguments. With 0 arguments, the loop body never executes.
0510Question 8
Medium
What is the output?
static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
System.out.println(factorial(1));
System.out.println(factorial(5));
System.out.println(factorial(0));factorial(1) and factorial(0) both hit the base case. factorial(5) = 5*4*3*2*1.
11201Question 9
Hard
What is the output?
static void display(int a, double b) {
System.out.println("int, double");
}
static void display(double a, int b) {
System.out.println("double, int");
}
display(5, 3.0);
display(3.0, 5);The compiler matches arguments to parameter types in order.
int, doubledouble, intQuestion 10
Hard
What is the output?
static int count = 0;
static void recursive(int n) {
if (n <= 0) return;
count++;
recursive(n - 1);
count++;
System.out.println("n=" + n + " count=" + count);
}
recursive(3);
System.out.println("Final count: " + count);count++ happens before AND after the recursive call. The print happens after the recursive call returns.
n=1 count=4n=2 count=5n=3 count=6Final count: 6Question 11
Hard
What is the output?
static String mystery(int n) {
if (n <= 0) return "";
return mystery(n - 1) + n;
}
System.out.println(mystery(5));The recursive call happens BEFORE the concatenation. The deepest call returns first.
12345Question 12
Hard
What is the output?
static void test(Object o) {
System.out.println("Object");
}
static void test(String s) {
System.out.println("String");
}
static void test(int i) {
System.out.println("int");
}
test("Hello");
test(5);
test(null);When multiple methods match, the most specific one is chosen. String is more specific than Object. null matches both Object and String.
StringintStringMixed & Application Questions
Question 1
Easy
What is the output?
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
System.out.println(isPrime(7));
System.out.println(isPrime(4));
System.out.println(isPrime(1));7 has no divisors from 2 to sqrt(7). 4 is divisible by 2. 1 is less than 2.
truefalsefalseQuestion 2
Easy
What is the output?
static String repeat(String s, int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += s;
}
return result;
}
System.out.println(repeat("Ha", 3));
System.out.println(repeat("*", 5));The method concatenates the string s with itself n times.
HaHaHa*****Question 3
Easy
What is the output?
static int doubleIt(int n) {
return n * 2;
}
System.out.println(doubleIt(doubleIt(3)));
System.out.println(doubleIt(5) + doubleIt(10));The inner doubleIt() call is evaluated first, and its result is passed to the outer call.
1230Question 4
Medium
What is the output?
static int fibonacci(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
for (int i = 0; i < 7; i++) {
System.out.print(fibonacci(i) + " ");
}Fibonacci: 0, 1, 1, 2, 3, 5, 8, ...
0 1 1 2 3 5 8 Question 5
Medium
What is the output?
static void modifyString(String s) {
s = s + " World";
System.out.println("Inside: " + s);
}
String msg = "Hello";
modifyString(msg);
System.out.println("Outside: " + msg);String is an object, but it is immutable. Reassigning the local variable does not affect the caller.
Inside: Hello WorldOutside: HelloQuestion 6
Medium
What is the output?
static int compute(int x) {
if (x > 0) {
return x + compute(x - 2);
}
return 0;
}
System.out.println(compute(5));
System.out.println(compute(6));Trace: compute(5) = 5 + compute(3) = 5 + 3 + compute(1) = 5 + 3 + 1 + compute(-1) = 9.
912Question 7
Medium
What is the difference between method overloading and method overriding?
One happens at compile time within a class. The other happens at runtime between classes.
Overloading occurs within the same class — multiple methods with the same name but different parameter lists. Resolved at compile time. Overriding occurs in a subclass — a method with the same name and same parameter list as a parent class method. Resolved at runtime (dynamic dispatch).
Question 8
Hard
What is the output?
static int mystery(int a, int b) {
if (b == 0) return a;
return mystery(b, a % b);
}
System.out.println(mystery(48, 18));
System.out.println(mystery(100, 25));This is a well-known algorithm. Trace: mystery(48, 18) -> mystery(18, 12) -> mystery(12, 6) -> mystery(6, 0) -> 6.
625Question 9
Hard
Explain why Java is called 'pass-by-value' even when passing objects. What exactly is being copied?
Think about what a reference variable holds and what gets copied when you pass it to a method.
Java is pass-by-value because the value of the variable is always copied. For primitives, the value is the actual data (e.g., 42). For objects, the value is the reference (memory address), not the object itself. The method receives a copy of this reference. Both the caller's reference and the method's reference point to the same object, so modifications through either reference affect the same object. However, reassigning the method's reference does not affect the caller's reference.
Question 10
Hard
What is the output?
static void hanoi(int n, char from, char to, char aux) {
if (n == 0) return;
hanoi(n - 1, from, aux, to);
System.out.println(from + " -> " + to);
hanoi(n - 1, aux, to, from);
}
hanoi(3, 'A', 'C', 'B');Tower of Hanoi with 3 disks produces 7 moves (2^n - 1).
A -> CA -> BC -> BA -> CB -> AB -> CA -> CMultiple Choice Questions
MCQ 1
What is the return type of a method that does not return any value?
Answer: B
B is correct.
B is correct.
void indicates that a method does not return any value. null (A) is a value, not a type. None (C) is used in Python, not Java. empty (D) is not a keyword.MCQ 2
Which of the following is valid method overloading?
Answer: B
B is correct. Overloading requires the same name with different parameter lists (number, types, or order). Differing only in return type (A) or access modifier (D) causes a compilation error. Different names (C) are just different methods, not overloading.
B is correct. Overloading requires the same name with different parameter lists (number, types, or order). Differing only in return type (A) or access modifier (D) causes a compilation error. Different names (C) are just different methods, not overloading.
MCQ 3
What happens if a non-void method does not have a return statement?
Answer: C
C is correct. The Java compiler enforces that every non-void method must return a value on all possible code paths. A missing return statement results in a compilation error: 'missing return statement'.
C is correct. The Java compiler enforces that every non-void method must return a value on all possible code paths. A missing return statement results in a compilation error: 'missing return statement'.
MCQ 4
In Java, the main method must be:
Answer: A
A is correct. The JVM calls the main method without creating an object, so it must be static. It must be public so the JVM can access it from outside the class. The exact signature is:
A is correct. The JVM calls the main method without creating an object, so it must be static. It must be public so the JVM can access it from outside the class. The exact signature is:
public static void main(String[] args).MCQ 5
What is Java's parameter passing mechanism?
Answer: C
C is correct. Java is strictly pass-by-value for ALL types. For primitives, the value is copied. For objects, the value of the reference (memory address) is copied. The method cannot change what the caller's variable points to, only the state of the pointed-to object.
C is correct. Java is strictly pass-by-value for ALL types. For primitives, the value is copied. For objects, the value of the reference (memory address) is copied. The method cannot change what the caller's variable points to, only the state of the pointed-to object.
MCQ 6
What is the output of this code?
static int add(int a, int b) { return a + b; }
static double add(int a, int b) { return a + b; }
Answer: C
C is correct. These two methods have the same name and the same parameter list (int, int). They differ only in return type, which is not sufficient for overloading. The compiler reports a duplicate method error.
C is correct. These two methods have the same name and the same parameter list (int, int). They differ only in return type, which is not sufficient for overloading. The compiler reports a duplicate method error.
MCQ 7
Where must a varargs parameter appear in a method's parameter list?
Answer: C
C is correct. A varargs parameter must be the last parameter in the list.
C is correct. A varargs parameter must be the last parameter in the list.
void example(String label, int... values) is valid. void example(int... values, String label) is not. This ensures the compiler can unambiguously determine which arguments belong to the varargs.MCQ 8
What happens when a recursive method has no base case?
Answer: C
C is correct. Without a base case, the method calls itself indefinitely. Each call adds a frame to the call stack. When the stack runs out of space, the JVM throws a
C is correct. Without a base case, the method calls itself indefinitely. Each call adds a frame to the call stack. When the stack runs out of space, the JVM throws a
StackOverflowError. It does not run forever (A) because stack space is finite.MCQ 9
What is the output?
static void test(int... a) { System.out.println("varargs"); }
static void test(int a) { System.out.println("single"); }
test(5);Answer: B
B is correct. When a method call matches both a specific parameter and a varargs parameter, the specific parameter wins.
B is correct. When a method call matches both a specific parameter and a varargs parameter, the specific parameter wins.
test(5) matches test(int a) exactly, so "single" is printed. Varargs has lower priority in overload resolution.MCQ 10
Can a static method access instance variables directly?
Answer: C
C is correct. Static methods do not have an implicit
C is correct. Static methods do not have an implicit
this reference because they belong to the class, not to any specific object. To access instance variables from a static method, you need an explicit object reference. Static methods can directly access static variables and call other static methods.MCQ 11
What is the time complexity of the naive recursive Fibonacci implementation?
Answer: C
C is correct. The naive recursive Fibonacci has exponential time complexity O(2^n) because each call branches into two sub-calls, and many subproblems are recomputed. For example, fibonacci(5) computes fibonacci(3) twice and fibonacci(2) three times. Memoization or iteration reduces this to O(n).
C is correct. The naive recursive Fibonacci has exponential time complexity O(2^n) because each call branches into two sub-calls, and many subproblems are recomputed. For example, fibonacci(5) computes fibonacci(3) twice and fibonacci(2) three times. Memoization or iteration reduces this to O(n).
MCQ 12
What is the correct syntax for calling a static method from another class?
Answer: A
A is correct. Static methods are called using the class name:
A is correct. Static methods are called using the class name:
Math.sqrt(25), Arrays.sort(arr). Option C creates an object first, which is unnecessary for static methods. Option D uses arrow syntax which is not valid in Java.Coding Challenges
Challenge 1: Calculate Power Without Math.pow()
EasyAarav needs a method that calculates base raised to the power of exponent using a loop (not Math.pow()). Write a method power(int base, int exp) that returns the result. Test with power(2, 10) and power(5, 3).
Sample Input
(No input required)
Sample Output
2^10 = 1024
5^3 = 125
Use a for loop. Assume exponent is non-negative.
public class PowerCalc {
static long power(int base, int exp) {
long result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}
public static void main(String[] args) {
System.out.println("2^10 = " + power(2, 10));
System.out.println("5^3 = " + power(5, 3));
}
}Challenge 2: Count Digits Using Recursion
EasyWrite a recursive method countDigits(int n) that returns the number of digits in a positive integer. Test with 12345 and 7.
Sample Input
(No input required)
Sample Output
Digits in 12345: 5
Digits in 7: 1
Use recursion, not String conversion. Base case: single digit number.
public class CountDigits {
static int countDigits(int n) {
if (n < 10) return 1;
return 1 + countDigits(n / 10);
}
public static void main(String[] args) {
System.out.println("Digits in 12345: " + countDigits(12345));
System.out.println("Digits in 7: " + countDigits(7));
}
}Challenge 3: Overloaded Area Calculator
EasyWrite three overloaded methods named area(): one for a circle (takes radius), one for a rectangle (takes length and width), and one for a triangle (takes base and height). Test all three.
Sample Input
(No input required)
Sample Output
Circle area: 78.54
Rectangle area: 30.00
Triangle area: 24.00
Use method overloading. Return double. Format output to 2 decimal places.
public class AreaCalculator {
static double area(double radius) {
return Math.PI * radius * radius;
}
static double area(double length, double width) {
return length * width;
}
static double area(double base, double height, boolean isTriangle) {
return 0.5 * base * height;
}
public static void main(String[] args) {
System.out.printf("Circle area: %.2f%n", area(5.0));
System.out.printf("Rectangle area: %.2f%n", area(5.0, 6.0));
System.out.printf("Triangle area: %.2f%n", area(8.0, 6.0, true));
}
}Challenge 4: Sum of Digits Using Recursion
MediumPriya wants a recursive method sumOfDigits(int n) that returns the sum of all digits in a number. Test with 12345 (expected: 15) and 9999 (expected: 36).
Sample Input
(No input required)
Sample Output
Sum of digits of 12345: 15
Sum of digits of 9999: 36
Use recursion. Extract last digit with n % 10, remove it with n / 10.
public class SumOfDigits {
static int sumOfDigits(int n) {
if (n == 0) return 0;
return n % 10 + sumOfDigits(n / 10);
}
public static void main(String[] args) {
System.out.println("Sum of digits of 12345: " + sumOfDigits(12345));
System.out.println("Sum of digits of 9999: " + sumOfDigits(9999));
}
}Challenge 5: Palindrome Checker Using Recursion
MediumWrite a recursive method isPalindrome(String s, int left, int right) that checks if a string is a palindrome. Test with "racecar" and "hello".
Sample Input
(No input required)
Sample Output
racecar is a palindrome: true
hello is a palindrome: false
Use recursion. Compare characters from both ends moving inward.
public class PalindromeRecursive {
static boolean isPalindrome(String s, int left, int right) {
if (left >= right) return true;
if (s.charAt(left) != s.charAt(right)) return false;
return isPalindrome(s, left + 1, right - 1);
}
public static void main(String[] args) {
String s1 = "racecar";
String s2 = "hello";
System.out.println(s1 + " is a palindrome: " + isPalindrome(s1, 0, s1.length() - 1));
System.out.println(s2 + " is a palindrome: " + isPalindrome(s2, 0, s2.length() - 1));
}
}Challenge 6: Binary Search Using Recursion
MediumRohan needs a recursive binary search method that returns the index of a target in a sorted array, or -1 if not found. Test with array {2, 5, 8, 12, 16, 23, 38, 56, 72, 91} searching for 23 and 50.
Sample Input
(No input required)
Sample Output
Index of 23: 5
Index of 50: -1
Use recursion. The method should take the array, target, low index, and high index.
public class BinarySearch {
static int binarySearch(int[] arr, int target, int low, int high) {
if (low > high) return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) return binarySearch(arr, target, mid + 1, high);
return binarySearch(arr, target, low, mid - 1);
}
public static void main(String[] args) {
int[] arr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
System.out.println("Index of 23: " + binarySearch(arr, 23, 0, arr.length - 1));
System.out.println("Index of 50: " + binarySearch(arr, 50, 0, arr.length - 1));
}
}Challenge 7: Tower of Hanoi
HardWrite a recursive solution for the Tower of Hanoi problem with n disks. Print each move in the format "Disk X: A -> C". Test with n=3 and rods A (source), C (destination), B (auxiliary).
Sample Input
(No input required)
Sample Output
Disk 1: A -> C
Disk 2: A -> B
Disk 1: C -> B
Disk 3: A -> C
Disk 1: B -> A
Disk 2: B -> C
Disk 1: A -> C
Use recursion. Print the disk number in each move.
public class TowerOfHanoi {
static void hanoi(int n, char from, char to, char aux) {
if (n == 0) return;
hanoi(n - 1, from, aux, to);
System.out.println("Disk " + n + ": " + from + " -> " + to);
hanoi(n - 1, aux, to, from);
}
public static void main(String[] args) {
hanoi(3, 'A', 'C', 'B');
}
}Challenge 8: Generate All Permutations
HardWrite a recursive method that prints all permutations of a given string. Test with the string "ABC".
Sample Input
(No input required)
Sample Output
ABC
ACB
BAC
BCA
CBA
CAB
Use recursion with character swapping. The method should accept the string as a char array and the current index.
public class Permutations {
static void permute(char[] arr, int index) {
if (index == arr.length - 1) {
System.out.println(new String(arr));
return;
}
for (int i = index; i < arr.length; i++) {
char temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
permute(arr, index + 1);
temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
permute("ABC".toCharArray(), 0);
}
}Challenge 9: Varargs Statistics Calculator
HardWrite three varargs methods: min(int... nums), max(int... nums), and average(int... nums). Test with the values 45, 78, 23, 91, 56.
Sample Input
(No input required)
Sample Output
Min: 23
Max: 91
Average: 58.60
Use varargs. Handle edge case of zero arguments. Return double for average.
public class StatsCalc {
static int min(int... nums) {
int result = nums[0];
for (int n : nums) {
if (n < result) result = n;
}
return result;
}
static int max(int... nums) {
int result = nums[0];
for (int n : nums) {
if (n > result) result = n;
}
return result;
}
static double average(int... nums) {
int sum = 0;
for (int n : nums) sum += n;
return (double) sum / nums.length;
}
public static void main(String[] args) {
System.out.println("Min: " + min(45, 78, 23, 91, 56));
System.out.println("Max: " + max(45, 78, 23, 91, 56));
System.out.printf("Average: %.2f%n", average(45, 78, 23, 91, 56));
}
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Java with a live mentor?
Explore our Java Masterclass