Passing immutable types by reference in Java and C#

To many, it should be obvious what the following code prints:

public static void main(String[] args){
     int x=0;
     SomeMethod(x);
     System.out.println(x);
}

protected static void SomeMethod(int x){
     x=1;
}

The code prints 0, because “int” is a native type and is passed by value. But, what if we replace “int” with “Integer”?

public static void main(String[] args){
     Integer x=0;
     SomeMethod(x);
     System.out.println(x);
}

protected static void SomeMethod(Integer x){
     x=1;
}

This is where a lot of people get confused. Integer is an object type, and will be passed by reference, but the program still prints 0. Why? Even though x is a reference to an object, Integer is an immutable type, and the assignment “x=1” is actually equivalent to “x=new Integer(1)”. This actually changes the value of x, rather than the value pointed to by x.

Fortunately this case is rarely the source of errors since it’s considered bad design to return values through parameters.

Although the above code is in Java, you will run into similar behavior with C# immutable types.

Leave a Reply