You cannot change the value of the variable i in main from method p1 , because the argument is passed by value: parameter i in p1 completely separate from i , it's just that they have the same value at the beginning of the method. Java always uses pass-by-value semantics, but when a parameter type is a class, it refers to a value.
In fact, you do not change the value of arr , either - this is a reference to the same array as before, but the value in the array has been changed. And this is what you cannot do with Integer , because Integer is an immutable type.
If you need a mutable class like Integer , you can use AtomicInteger :
public static void main(String[] args) { AtomicInteger i = new AtomicInteger(0); modify(i); System.out.println(i); } private static void modify(AtomicInteger x) { x.set(2); }
I usually did not do this, however, I usually try not to change the objects referenced by the method parameters. Instead, I write methods that compute a single result and return it.
source share