0
public class Autoboxing {
public static void main(String[] args) {
   int x=10;
    Integer oldValue=x;
    change(oldValue);
    System.out.println("value:"+oldValue);
}
static void change(Integer value){
    value=100;
}

}

Hi, I am trying to autobox a int value into Integer type. Then pass the Integer object to a method to change the number . But the number doesnt change. it still prints out 10? Could some one spot my error. Thanks in advance.

  • Java is pass-by-value not by reference, that means that, after calling method `change` value of `oldValue` would not be affected with modifications that you've done in the called method. – justRadojko Feb 12 '16 at 14:10
  • 1
    static int change(int value){ value=100; return 100; } public static void main(String[] args) { // TODO code application logic here int x=10; Integer oldValue=x; int z = change(oldValue); System.out.println("value:"+z); } this will give you 100 – Akhil Feb 12 '16 at 14:18

1 Answers1

1

Wrappers of primitive types are immodifiables.

It means that you can't change the content of an Integer, but only reassign it.

You will have the same behaviour with any immodifiable class. As an example with String.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56