Java Pass by Value Explained with Real Examples

0

1. Pass by Value in Java

Java uses Pass by Value for method calls.

This means Java copies values when arguments are passed to methods.

The original variables are not directly passed into methods.


2. Why Pass by Value is Used

Pass by value helps Java maintain safer and more predictable memory behavior.

  • a. Protects original primitive values
  • b. Simplifies memory management
  • c. Prevents direct variable modification
  • d. Improves program reliability
  • e. Makes method execution predictable
  • f. Reduces unintended side effects

3. Where Pass by Value is Used

Pass by value behavior is used in all Java method calls.

  • a. Primitive variable methods
  • b. Object method calls
  • c. Array operations
  • d. Constructor calls
  • e. Collection handling
  • f. Utility methods

4. Understanding Pass by Value

Java copies argument values into method parameters.

The copied value is stored separately inside the method.


4.1 Basic Primitive Example

public class Main {

    static void change(int number) {

        number = 100;

        System.out.println(number);
    }

    public static void main(String[] args) {

        int value = 50;

        change(value);

        System.out.println(value);
    }
}

The original variable remains unchanged because Java copied the value 50 into the parameter.


Primitive variables always pass copied values.


5. Primitive Data Type Passing

Primitive variables store actual values directly.


5.1 Integer Passing Example

public class Main {

    static void update(int x) {

        x = 500;
    }

    public static void main(String[] args) {

        int number = 10;

        update(number);

        System.out.println(number);
    }
}

The value of number remains 10 because only the copied value changes.


5.2 Double Passing Example

public class Main {

    static void modify(double price) {

        price = 99.99;
    }

    public static void main(String[] args) {

        double amount = 50.5;

        modify(amount);

        System.out.println(amount);
    }
}

The original amount variable remains unchanged.


6. Reference Variables and Pass by Value

Objects are accessed using references.

Java copies the reference value during method calls.


6.1 Example Using Object

class Student {

    int marks;
}

public class Main {

    static void update(Student s) {

        s.marks = 95;
    }

    public static void main(String[] args) {

        Student obj = new Student();

        update(obj);

        System.out.println(obj.marks);
    }
}

The object data changes because both references point to the same object.


Java still uses pass by value even when objects are involved.


7. Understanding Reference Copying

Object variables store memory addresses called references.


7.1 Reference Copy Flow

Original Reference Copied Parameter Reference
Object Address Same Object Address

Both references point to the same object in heap memory.


7.2 Example with Array

public class Main {

    static void change(int[] values) {

        values[0] = 999;
    }

    public static void main(String[] args) {

        int[] numbers = {1, 2, 3};

        change(numbers);

        System.out.println(numbers[0]);
    }
}

The array content changes because the copied reference points to the same array object.


8. Internal Working of Pass by Value

Java creates separate parameter variables during method execution.


8.1 Internal Execution Steps

  • a. Method call occurs
  • b. Stack frame is created
  • c. Argument values are copied
  • d. Method logic executes
  • e. Stack frame is removed after completion

8.2 Stack Memory Example

public class Main {

    static void show(int value) {

        System.out.println(value);
    }

    public static void main(String[] args) {

        int number = 25;

        show(number);
    }
}

The value 25 is copied into the method parameter stored inside a separate stack frame.


9. Object Reassignment Inside Methods

Changing the copied reference itself does not affect the original reference variable.


9.1 Example of Object Reassignment

class Student {

    int marks = 50;
}

public class Main {

    static void change(Student s) {

        s = new Student();

        s.marks = 100;
    }

    public static void main(String[] args) {

        Student obj = new Student();

        change(obj);

        System.out.println(obj.marks);
    }
}

The original object remains unchanged because only the copied reference was reassigned.


Reassigning copied references does not change the original reference variable.


10. Modifying Object Data

Although references are copied, both references can still access the same object.


10.1 Example of Shared Object Access

class Employee {

    String name = "Amit";
}

public class Main {

    static void update(Employee e) {

        e.name = "Rahul";
    }

    public static void main(String[] args) {

        Employee obj = new Employee();

        update(obj);

        System.out.println(obj.name);
    }
}

The object data changes because both references point to the same heap object.


11. Heap Memory and Stack Memory

Java uses both heap memory and stack memory during method execution.


11.1 Stack Memory

  • a. Stores method calls
  • b. Stores local variables
  • c. Stores copied parameter values
  • d. Works in Last In First Out order

11.2 Heap Memory

  • a. Stores objects
  • b. Stores arrays
  • c. Shared using references
  • d. Managed by Garbage Collector

11.3 Memory Example

class Test {

    int value = 10;
}

public class Main {

    static void modify(Test t) {

        t.value = 50;
    }

    public static void main(String[] args) {

        Test obj = new Test();

        modify(obj);

        System.out.println(obj.value);
    }
}

The object exists in heap memory while the reference variables exist in stack memory.


Objects are never copied automatically during normal method calls.


12. Common Confusion About Pass by Reference

Many beginners incorrectly think Java uses pass by reference for objects.


12.1 Why Confusion Happens

Object data can change inside methods, which creates confusion.


class Box {

    int size = 10;
}

public class Main {

    static void change(Box b) {

        b.size = 99;
    }

    public static void main(String[] args) {

        Box obj = new Box();

        change(obj);

        System.out.println(obj.size);
    }
}

The object changes because both references point to the same object, not because Java uses pass by reference.


13. Real-World Practical Example

Pass by value behavior is commonly used in applications that update object data.


13.1 Student Marks Update System

class Student {

    int marks;
}

public class Main {

    static void addBonusMarks(Student s) {

        s.marks = s.marks + 5;
    }

    public static void main(String[] args) {

        Student student = new Student();

        student.marks = 80;

        addBonusMarks(student);

        System.out.println(student.marks);
    }
}

The method updates the same Student object stored in heap memory.


14. Method Calls and Stack Frames

Each method call creates a separate stack frame.


14.1 Stack Frame Example

public class Main {

    static void first(int x) {

        second(x);
    }

    static void second(int y) {

        System.out.println(y);
    }

    public static void main(String[] args) {

        first(10);
    }
}

Separate stack frames are created for first() and second().


14.2 Stack Cleanup

After method execution completes, Java automatically removes stack frames.


public class Main {

    static void test() {

        System.out.println("Done");
    }

    public static void main(String[] args) {

        test();
    }
}

The stack frame for test() is removed after execution finishes.


Stack memory is temporary while heap objects can exist longer.


15. Common Beginner Mistakes


15.1 Thinking Java Uses Pass by Reference

A very common mistake is assuming Java passes objects by reference.


class Demo {

    int value = 10;
}

public class Main {

    static void update(Demo d) {

        d = new Demo();
        d.value = 99;
    }

    public static void main(String[] args) {

        Demo obj = new Demo();

        update(obj);

        System.out.println(obj.value);
    }
}

The output remains 10 because the original reference is not modified.


15.2 Assuming Primitive Values Change

public class Main {

    static void change(int x) {

        x = 100;
    }

    public static void main(String[] args) {

        int a = 50;

        change(a);

        System.out.println(a);
    }
}

The value remains 50 because only a copy is modified inside the method.


15.3 Confusing Object Reassignment

class Test {

    int value = 20;
}

public class Main {

    static void modify(Test t) {

        t = new Test();
        t.value = 200;
    }

    public static void main(String[] args) {

        Test obj = new Test();

        modify(obj);

        System.out.println(obj.value);
    }
}

Reassigning the reference inside the method does not affect the original object.


16. Edge Cases in Pass by Value


16.1 Passing null References

class Data {

    int value = 10;
}

public class Main {

    static void show(Data d) {

        System.out.println(d.value);
    }

    public static void main(String[] args) {

        Data obj = null;

        show(obj);
    }
}

This code throws NullPointerException because the reference points to nothing.


16.2 Empty Object Modification

class Box {

    int size;
}

public class Main {

    static void update(Box b) {

        b.size = 50;
    }

    public static void main(String[] args) {

        Box obj = new Box();

        update(obj);

        System.out.println(obj.size);
    }
}

Even empty objects can be modified through references.


16.3 Large Object Handling

Large objects are still passed efficiently because only references are copied.


class BigData {

    int[] values = new int[1000];
}

public class Main {

    static void process(BigData data) {

        data.values[0] = 999;
    }

    public static void main(String[] args) {

        BigData obj = new BigData();

        process(obj);

        System.out.println(obj.values[0]);
    }
}

Only the reference is copied, not the entire object.


17. Best Practices for Pass by Value


17.1 Avoid Unnecessary Object Mutation

Modify objects carefully inside methods to avoid unexpected side effects.


static void updateValue(int value) {

    value = value + 10;
}

Keeping logic simple reduces confusion.


17.2 Use Immutable Objects When Possible

Immutable objects prevent accidental modifications.


String text = "Java";

String objects are immutable, so their value cannot be changed.


17.3 Clearly Separate Input and Output

Methods should clearly define what is input and what is output.


static int calculate(int a, int b) {

    return a + b;
}

Clear method design improves readability and debugging.


Understanding pass by value helps avoid logic errors in Java programs.


18. Important Points to Remember

  • a. Java is always pass by value
  • b. Primitive values are copied directly
  • c. Object references are also copied
  • d. Objects can still be modified through copied references
  • e. Reassigning references does not affect original objects
  • f. Stack memory stores method calls and parameters
  • g. Heap memory stores actual objects
  • h. Misunderstanding leads to many logical errors

Java’s pass by value mechanism ensures predictable behavior by copying values during method calls. Understanding the difference between primitive copying and reference copying is essential for writing correct and efficient Java programs, especially when working with objects, arrays, and complex data structures.

Post a Comment

0Comments
Post a Comment (0)