4

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.

Arvind Chavhan
  • 488
  • 1
  • 6
  • 14
  • 4
    `Java` --> `pass by value`. – SatyaTNV Sep 23 '15 at 18:24
  • 3
    possible 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
  • 1
    Java 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 Answers2

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
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