Value vs Reference Passing in Java: Concepts, Stack vs Heap, and Code Examples
This article explains the difference between value passing and reference passing in Java, clarifies how primitive and object types are stored in stack and heap, and demonstrates the behavior with concrete code examples showing how modifications affect (or do not affect) the original arguments.
When a parameter is passed to a method, two cases arise: value passing and reference passing. Understanding these concepts is essential before debating whether Java uses value or reference passing.
Value Passing copies the actual value of the argument into the parameter, so changes to the parameter do not affect the original argument. This can be inefficient for large data structures.
Reference Passing passes the address of an object, allowing the method to operate on the original data. The parameter and argument point to the same memory location, so modifications affect the original object.
Java distinguishes between primitive types (e.g., int ) that store actual values on the stack, and reference types (e.g., String ) that store references to objects on the heap. The stack provides fast access but requires fixed size and lifetime, while the heap allows dynamic allocation managed by the garbage collector.
public class ItXianYuDemo {
public static void main(String[] args) {
int age = 20;
modify(age);
System.out.println(age);
}
private static void modify(int muage) {
muage = 30;
}
}In this example, age is a primitive; the method receives a copy, so the printed value remains 20.
public class ItXianYuDemo {
public static void main(String[] args) {
Writer a = new Writer(18);
Writer b = new Writer(18);
modify(a, b);
System.out.println(a.getAge());
System.out.println(b.getAge());
}
private static void modify(Writer mu1, Writer mu2) {
mu1.setAge(30);
mu2 = new Writer(18);
mu2.setAge(30);
}
}Here, a and b are reference types; the method receives copies of the references. Changing mu1 's state affects a , while reassigning mu2 does not affect b because only the local copy is changed.
The accurate statement is that Java always performs value passing; when the value is a reference, the address is passed, which some describe as “reference passing” but is still passing a value (the reference).
IT Xianyu
We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.