0

This Program prints 1 but It should print 2. Can anyone explain this to me ?

public class Exp {

public static void main(String[] args) {
   Integer abc = 1;
   sum(abc);
   System.out.println(abc);

}

private static void sum(Integer abc) {
    abc = 2;

}

}

Ngupta
  • 319
  • 4
  • 19
  • I still do not understand. Can someone Please explain what is different in case of Wrapper classes – Ngupta Jun 10 '16 at 21:03
  • 1
    Nothing is different. You'll get the same result if you use a `String` for example. Changing the value of the method parameter doesn't change the value of the variable used for the argument in the method. – Jon Skeet Jun 10 '16 at 21:05
  • The universal rule is that you can change properties of objects passed into a method (assuming the object is mutable), but you can't change what object it is. – Louis Wasserman Jun 10 '16 at 21:09
  • Wrapper classes are immutable, that means you can't change its value. In your case "abc" variable in sum method will refer to different value from the one that is refereed by "abc" variable in main. – AmjadD Jun 10 '16 at 21:11
  • @LouisWasserman, the catch there - and the problem in this particular case - is that wrapper classes like String and Integer are immutable. That, combined with auto-boxing/unboxing means that they basically behave like primitives. So, the line `abc = 2;` actually creates a new variable to reference via `abc`, rather than altering the value of the existing variable. – James Tanner Jun 10 '16 at 21:12
  • 1
    @JamesTanner, eh? Not sure what difference that makes. You can't write `methodParameter = whatever` and expect `methodParameter` to change outside the method, whether it's a primitive, reference to a mutable type, or reference to an immutable type. – Louis Wasserman Jun 10 '16 at 21:13
  • @LouisWasserman, ah. I misunderstood what you meant by "what object it is". For some reason, I was thinking about type. Yes, if you assign the variable to a new object, the old object wouldn't change. So `myObject = new Thing();` doesn't work, but `myObject.someValue = new Thing();` does, because the reference `myObject` still points to the same object in memory. – James Tanner Jun 10 '16 at 21:18

0 Answers0