Java Interview Questions
Java Methods and Recursion - Theory Questions
1. What is a method in Java and what are its advantages?
A method in Java is a block of code that performs a specific task and can be reused throughout the program. Advantages include:
- Code Reusability: Write once, use multiple times
- Modularity: Break complex problems into smaller parts
- Abstraction: Hide implementation details
- Maintainability: Easier to debug and modify
- Testing: Individual methods can be tested separately
2. What is the syntax of a method declaration in Java?
Basic method syntax:
[access-modifier] [non-access-modifiers] return-type method-name(parameter-list) {
// method body
}
Example:
public static int addNumbers(int a, int b) {
return a + b;
}
3. What is the difference between parameters and arguments?
Parameters: Variables defined in the method declaration
Arguments: Actual values passed to the method when called
Example:
// a and b are parameters
void multiply(int a, int b) { ... }
// 5 and 10 are arguments
multiply(5, 10);
4. What are the different types of methods in Java?
Instance methods: Belong to object instance, can access instance variables
Static methods: Belong to class, can be called without object
Abstract methods: Declared without implementation in abstract class/interface
Final methods: Cannot be overridden by subclasses
Synchronized methods: Thread-safe, only one thread can execute at a time
Native methods: Implemented in other languages (like C/C++)
5. What is method overloading in Java?
Method overloading is having multiple methods with same name but different parameters in the same class. Differences can be in:
- Number of parameters
- Type of parameters
- Order of parameters
void display(int a) { ... }
void display(String s) { ... }
void display(int a, String s) { ... }
Note: Return type alone cannot differentiate overloaded methods
6. What is method signature in Java?
Method signature consists of the method name and parameter list (types and order). It does NOT include:
- Return type
- Access modifiers
- Exception list
Example: For method public int calculate(int a, double b) throws Exception
Signature is: calculate(int, double)
7. What is pass-by-value in Java methods?
Java uses pass-by-value for all method parameters:
- For primitive types: Copy of the value is passed
- For object references: Copy of the reference is passed
This means:
- Modifying primitive parameters doesn't affect original
- Modifying object through reference affects original object
- Reassigning object reference doesn't affect original reference
8. What is variable-length argument (varargs) in Java?
Varargs allows methods to accept zero or more arguments of specified type:
void printNumbers(int... numbers) {
for (int num : numbers) {
System.out.println(num);
}
}
Rules:
- Only one varargs parameter per method
- Must be the last parameter in method
- Internally treated as array
9. What is recursion and what are its key components?
Recursion is a technique where a method calls itself to solve a problem. Key components:
- Base case: Condition that stops recursion
- Recursive case: Method calls itself with modified parameters
Example (factorial):
int factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive case
}
10. What are the advantages and disadvantages of recursion?
Advantages:
- Elegant solution for problems with recursive nature
- Reduces code complexity for certain problems
- Natural fit for tree/graph traversal
Disadvantages:
- Stack overflow: Deep recursion can cause StackOverflowError
- Memory overhead: Each call adds stack frame
- Performance: Usually slower than iterative solutions
- Debugging difficulty: Harder to trace execution
11. What is tail recursion and how is it optimized?
Tail recursion occurs when the recursive call is the last operation in the method:
int factorial(int n, int accumulator) {
if (n == 0) return accumulator;
return factorial(n - 1, n * accumulator); // tail call
}
Optimization: Some compilers can optimize tail recursion to use constant stack space (tail call optimization), but Java doesn't guarantee this optimization.
12. What is the difference between direct and indirect recursion?
Direct recursion: Method calls itself directly
void methodA() {
// some code
methodA(); // direct call
}
Indirect recursion: Method A calls method B, which calls method A
void methodA() {
methodB();
}
void methodB() {
methodA();
}
13. How do you prevent infinite recursion?
Ways to prevent infinite recursion:
- Always have a base case that will eventually be reached
- Ensure parameters move toward base case in recursive call
- Use loop counters or depth limits
- Validate input parameters before recursion
Example of safe recursion:
void countdown(int n) {
if (n <= 0) return; // base case
System.out.println(n);
countdown(n - 1); // moving toward base case
}
14. What are some common problems solved using recursion?
Classic recursive problems:
- Factorial calculation
- Fibonacci series
- Tower of Hanoi
- Binary tree traversals (inorder, preorder, postorder)
- Depth-first search in graphs
- Backtracking algorithms (N-Queens, Sudoku)
- Merge sort and Quick sort
15. What is method hiding in Java?
Method hiding occurs when a subclass defines a static method with same signature as static method in superclass:
class Parent {
static void display() { System.out.println("Parent"); }
}
class Child extends Parent {
static void display() { System.out.println("Child"); } // method hiding
}
Unlike overriding, the method called depends on reference type, not object type.
16. What is the 'return' statement and its various uses?
The return statement:
- Exits from the current method
- Returns control to the caller
- Can return a value (for non-void methods)
Examples:
return; // for void methods
return value; // for value-returning methods
return (a > b) ? a : b; // with ternary operator
return calculateResult(); // returning method result
17. What are access modifiers and how do they affect methods?
Access modifiers control method visibility:
- public: Accessible from anywhere
- protected: Accessible within package and subclasses
- default (no modifier): Accessible only within package
- private: Accessible only within same class
These enforce encapsulation and control API exposure.
18. What is the call stack and how does it relate to recursion?
The call stack is a stack data structure that stores information about active method calls. In recursion:
- Each recursive call pushes a new stack frame
- Each return pops a stack frame
- Deep recursion can cause stack overflow
- Stack frame contains parameters, local variables, and return address
Understanding the call stack is crucial for debugging recursive methods.
19. How do you convert recursive solutions to iterative ones?
Common techniques:
- Use loops instead of recursive calls
- Replace recursion stack with explicit stack data structure
- Use accumulator variables for tail recursion
- Maintain state using while loops with conditions
Example (factorial):
// Recursive
int fact(int n) { return (n == 0) ? 1 : n * fact(n-1); }
// Iterative
int fact(int n) { int result = 1; for(int i=1; i<=n; i++) result *= i; return result; }
20. What are the best practices for writing methods and recursion?
Method best practices:
- Single responsibility principle
- Descriptive names that indicate purpose
- Reasonable parameter count (max 3-4)
- Use final for parameters that shouldn't change
- Document with JavaDoc
Recursion best practices:
- Always define base case first
- Ensure progress toward base case
- Consider stack depth limitations
- Use memoization for repeated calculations
- Prefer iteration for simple cases