I know java is pass by reference but only for Java Objects. But why it is not applicable for Java Wrapper classes? Are Wrapper classes such as Integer, Float, Double pass by reference or pass by value? Because whenever I pass object of such classes in method and that changes some values, but outside of that method I am not getting updated Value.
Asked
Active
Viewed 7,031 times
4
-
4`Java` --> `pass by value`. – SatyaTNV Sep 23 '15 at 18:24
-
3possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – childofsoong Sep 23 '15 at 18:27
-
1Java is always pass by value. Wrapper classes may look like pass by reference but they are not. Here is a good read. http://javadude.com/articles/passbyvalue.htm – yogidilip Sep 23 '15 at 18:27
-
"I know java is pass by reference" - Houston we have a problem! This is basic fundamentals and yet it's not uncommon to see posts which state what they "know" but what they "know" is false(?). We either have an education or lack of education problem in this field... – ChiefTwoPencils Sep 23 '15 at 18:35
-
I'd be very curious to know how you have written a method "that changes some values" in immutable primitive wrappers. Would you care to post some code? – Mike Nakis Sep 23 '15 at 18:42
2 Answers
10
On top of pass by value
discussion, all wrapper classes in Java are immutable. They replicate the behaviour of primitives. You need to return the latest value back to see the changes.

Suresh Atta
- 120,458
- 37
- 198
- 307
-
Yes if I return value I am getting updated values. But I don't understand even java is pass by reference why it is not applicable for Wrapper Classes. – Arvind Chavhan Sep 23 '15 at 18:32
-
2@ArvindChavhan Because they are immutable :) Read about immutable classes. You'll understand : https://en.wikipedia.org/wiki/Primitive_wrapper_class – Suresh Atta Sep 23 '15 at 18:32
-
2@ArvindChavhan Java is NOT pass by reference. In Java, references are passed by value. – Peter Lawrey Sep 23 '15 at 18:48
-
1
-
1
-
Thanks @PeterLawrey Yeah I known but My my was with primitive which I understand that it is immutable. – Arvind Chavhan Sep 23 '15 at 18:52
-
In the case of `n++`, you don't need to return it, the original Integer n is increased automatically. – Eric Dec 17 '18 at 09:57
0
public static void main(String[] args) {
Integer i = 5;
display(i);
System.out.println(i);
}
private static void display(Integer i) {
i = 10;
}
The reason why i will not be updated because i=10 will use autoboxing here and it will be similar to i = new Integer(10)
Since i is pointing to a new memory address this change will not appear in main method