-1
public class Exa {
    public static void main(String[] args) {
        Integer b = new Integer(10);
        add(b);
        System.out.println(b.intValue());
   }

    public static void add(Integer b){
        int i = b.intValue();
        i += 3;
        b = new Integer(i);
        System.out.println("b="+b+",i="+i);
    }
}

I wrote the above code, and run output 10. Why did it not change?

Why output 10, please give detailed instructions,thanks!

VijayD
  • 826
  • 1
  • 11
  • 33

2 Answers2

2

The method local variable b in your main method is different from the method local variable in your add() method. Changing one won't affect the other.

b = new Integer(i);

Here you are referring to the variable in the add(Integer b) method not the variable in the main method.

Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.

(Extracted from this answer by erlando)

Community
  • 1
  • 1
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
0

The value does not change because you only assign b locally inside the add method. In Java, you can not change the value of an Integer, you only change the reference. To have the intended side effect, you could wrap b in an object.

Lars Gendner
  • 1,816
  • 2
  • 14
  • 24