Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Java Passes EVERYTHING by Value!

It’s a common misconception thinking (or worse teaching!) that, in Java, primitives are passed by value and objects by reference. Actually, everything in Java is passed by value as well as object references.

When a parameter is passed by value, an actual copy of it is really passed so that any change made will have only a local effect. For example:

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
  int a = 0;
  increment(a);
  System.out.println(a); //it prints 0 so increment didn't work as expected
}

public static int increment(int a) {
  ++a;
  System.out.println(a); //it prints 1
  return a;
}

As you can see the change made to the parameter passed to increment, that is a, affects only the local copy of it. This proves that Java passes primitives by value.

Well, this is no surprise to anyone since you already knew that.

I’ll prove now, that also object references are passed by value, that is only a copy of the reference is passed. Suppose you want to write a swap method to swap two integers. Since you know you can’t use primitives you might think to write the method using the wrapper class for int values, that is Integer. Let’s try that:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
  Integer a = new Integer(1);
  Integer b = new Integer(5);
  swap(a, b);
  System.out.println(b.intValue()); //it prints 5 so swap didn't work!
}

public static void swap(Integer a, Integer b) {
  Integer temp = a;
  a = b;
  b = temp;
  System.out.println(b.intValue()); //it prints 1!
}

This means that, even the object references are passed by value, as I stated at the beginning of this post!

What really happens is that, in case of references, a copy of the reference is passed and not the reference itself. This means that, if the class is not immutable, you can change it’s state but you CANNOT change the actual memory address the reference points to. Since Integer is an immutable class you cannot change its state. So if you want to swap two int values, you need to write your own class that wraps an int and provides a method to change the state of this instance variable. In this case you can pass the copy of the references to a swap method and call the method that lets you change the state of the object. This is left as an exercise though. :-)

Comments