Java always uses pass-by-value. However, the behavior differs slightly for primitive variables and object references.
For primitive data types, the actual value is copied and passed to the method. For objects, Java copies the reference value (memory address reference), not the actual object itself. This means the method receives a copy of the reference pointing to the same object.
As a result, a method can modify the internal state of the object through the copied reference, but it cannot change the original reference variable to point to a different object outside the method.
Key Points: • Java does not support true pass-by-reference. • Primitive values are copied and passed directly to methods. • For objects, a copy of the reference is passed, not the object itself. • Reassigning an object reference inside a method does not affect the original reference.
Example: If a Person object is passed to a method and the method updates the person's name, the change is visible outside the method because both references point to the same object. However, if the method creates a new Person object and assigns it to the parameter, the original reference remains unchanged.
Code Example:
class Person {
String name;
}
public class Test {
static void changeName(Person p) {
p.name = "John";
}
static void changeReference(Person p) {
p = new Person();
p.name = "Mike";
}
public static void main(String[] args) {
Person person = new Person();
person.name = "David";
changeName(person);System.out.println(person.name); // John
changeReference(person); System.out.println(person.name); // Still John
}
}Interview Tip: A concise interview answer is: Java is strictly pass-by-value. For primitives, the actual value is copied. For objects, a copy of the reference is passed. Therefore, methods can modify the object's state but cannot change the original object reference held by the caller.