Core Module
12 min forge

Java Methods and Parameter Passing

Understand how Java handles method calls, the stack frame, and the "Pass-by-Value" vs "Pass-by-Reference" debate.

Java Methods and Parameter Passing

πŸ›‘οΈ What is a Method?

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions in other languages.

⏰ When to Use

  • Code Reusability: Define code once and use it many times.
  • Decomposition: Breaking down complex logic into smaller, manageable chunks.
  • Abstraction: Hiding the implementation details from the caller.

πŸ“Š Complexity & Performance

  • Method Inlining: The JVM can optimize small methods by "inlining" them (replacing the call with the actual code), eliminating the overhead of a method call.
  • Recursion: Recursive methods use the execution stack. Deep recursion can lead to StackOverflowError. The time complexity depends on the recurrence relation.

πŸ’» Code Example: The Pass-by-Value Reality

In Java, everything is passed by value. For primitives, the actual value is copied. For objects, the value of the reference (memory address) is copied.

java Standard
public class ParameterPassing { public static void main(String[] args) { int x = 10; User user = new User("Alice"); modify(x, user); System.out.println("x: " + x); // Still 10 (Primitive copy) System.out.println("Name: " + user.name); // Now "Bob" (Reference copy) } static void modify(int val, User obj) { val = 20; // Only local 'val' changed obj.name = "Bob"; // Original object modified via copied reference obj = new User("Charlie"); // Local 'obj' now points to new memory // Original 'user' in main STILL points to the "Bob" object } } class User { String name; User(String n) { this.name = n; } }

⚠️ Interview Pitfalls

  1. Pass-by-Value Confusion: Many candidates claim Java is "Pass-by-Reference" for objects. Correct Answer: It is always "Pass-by-Value," but for objects, the value is the reference address.
  2. Infinite Recursion: Forgetting a base case in a recursive method is a classic mistake.
  3. Overloading vs. Overriding:
    • Overloading: Same name, different parameters (Compile-time polymorphism).
    • Overriding: Same name, same parameters in a subclass (Runtime polymorphism).
  4. Varargs misuse: Using Object... can lead to type-safety issues and performance overhead due to array creation. Use them sparingly.