Language Translator

Java Pass by Value

Er. Pradeip
0

Topic: Java Argument Passing | Concept: Pass by Value | Level: Beginner to Intermediate

Ever wondered whether Java passes method arguments by value or by reference? The answer is simple, but the details can be tricky. Java always uses pass-by-value — even for objects. Let’s break this down with examples, diagrams, and edge cases to fully understand how it works. Explore More Java Tips to sharpen your concepts!

Pass-by-Value: What It Really Means

Type What Gets Passed Can Original Change?
Primitive (int, double, etc.) Copy of the value No
Object (class instances) Copy of the reference Yes (modifies internal state)

Example: Passing Primitive

void modify(int num) {
    num = 10;
}

int x = 5;
modify(x);
System.out.println(x);  // Output: 5

Explanation: A copy of x is passed to the method. Changing num doesn’t affect x.

Example: Passing Object

class Box {
    int value = 5;
}

void modify(Box b) {
    b.value = 10;
}

Box box = new Box();
modify(box);
System.out.println(box.value);  // Output: 10

Explanation: A copy of the object reference is passed. Both b and box point to the same object, so changes affect the original object.

Important: You can change object contents but not reassign the original reference!

Example: Reassigning Object Inside Method

void reassign(Box b) {
    b = new Box();
    b.value = 99;
}

Box box = new Box();
reassign(box);
System.out.println(box.value);  // Output: 5

Explanation: Reassigning b only affects the local copy. box still points to the original object.

Summary Steps

  • Java always passes method arguments by value
  • For primitives, the value is passed → original stays unchanged
  • For objects, the reference is passed by value → internal state can change
  • Reassigning the reference inside a method doesn’t affect the original

Want more Java fundamentals? Visit our Java Blog | New tutorials every week!

Frequently Asked Questions

Q1. Is Java pass-by-reference for objects?
A: No, Java is strictly pass-by-value. For objects, the value of the reference is passed (i.e., a copy of the pointer).

Q2. Can I change the original object inside a method?
A: Yes, if you modify its fields. But if you reassign the object inside the method, it won’t affect the caller.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !