Pass by value or reference in Java

Something to keep in mind for programmers coming from a C/ C++ background who ‘grow up’ reading and learning about pass by value/ pass by reference of variables between functions – what happens in Java is a bit different from either of these paradigms. Consider what happens when the main method is called in the following Java code:

Java pass by value or reference

Java pass by value or reference

Can you guess what the output is?

The output is an array of 1’s, not an array of 0’s or 2’s. If the pass were by reference, then any changes made in the function test would be reflected in the main – meaning an array of 2’s would be printed. But this is not what happens. If the pass were by value, then an array of 0’s would be printed, because no matter what you do in test, the array will have a local value there and would not be reflected in the main, which will in turn retain the value the array was initialized with. So what is going on here? Why do we get an array of 1’s?

In Java, there are a handful of things to keep in mind:

  1. You can only pass by value
  2. Arrays are objects
  3. No objects are ever passed
  4. References to objects are passed by value
  5. References are pointers under the hood – Java does have pointers after all
  6. Objects can only be manipulated by references

Point number 4 is the most important one. The value of the reference to the array is passed to test – which means if you change the value of the array pointed to by the original reference within the called function, the change will reflect in the calling function. But you can’t make the reference point to something else in the called function, because you only have the value of the reference in the called function, not the reference itself.

For primitive types, however, i.e. if we were to talk about an int, for example, the value in the called function will be a copy of the original, and any changes made in the called function to that primitive type value will be local to the called function, and will not be seen in the calling function at all. This is why some people call Java impurely object oriented, because it allows the concept of certain things, i.e. primitive types, which are not objects, as opposed to purely object oriented programming languages like Python and Ruby where everything is an object.

Interesting.