When I have a function that changes an object, I expect the value of the object to change in the calling function (as described in Is Java “pass-by-reference” or “pass-by-value” since the reference is not changed). But it doesn't seem to work for the wrapper classes (like Integer
).
The following code:
public class Test
{
private static class MyInt
{
private int i;
public MyInt(int i)
{
this.i = i;
}
public int get()
{
return i;
}
public void set(int i)
{
this.i = i;
}
public void increment()
{
++this.i;
}
public String toString()
{
return Integer.toString(i);
}
}
public static void test(int a, Integer b, MyInt c)
{
++a;
++b;
System.out.println("b after increment is " + b);
c.increment();
}
public static void main(String[] args)
{
int a = 5;
Integer b = new Integer(5);
MyInt c = new MyInt(5);
test(a, b, c);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
generates the following output:
b after increment is 6
5
5
6
from which I can see that Integer
object does actually change inside the function, becoming 6, but it doesn't change the value of b
in main
. What is happening here? Are wrapper objects passed in some other way than regular objects?