Argument passing in Java

Often a method needs some initial information to start some computation. There are two ways to pass the same information to the method.

1. Pass by Value vs Pass by Reference

There are two ways to pass any argument to a method:

  • Pass by value : A copy of the passed argument is made and all the operations inside the method are performed on this copy.
  • Pass by reference : Only an alias or reference of the argument is passed to the method. So all the calculations happen on the original argument.

Some language support only one of the two ways, some languages (e.g. C++) support both.

2. Java passes arguments by Value

Java uses pass by value( or some may argue a hybrid of the two) to pass the arguments to a method. The overall effect differs and depends on whether a primitive or a non-primitive type is passed.

  • If a primitive type is passed, Java copies the value of the argument into a new variable and this copy is used inside the method. Any modification made to this copy inside the method won’t be visible from outside.
  • If a non-primitive type is passed, Java copies the value of the object-reference(only reference and not the entire object) into a new reference-variable and this new variable is used inside the method. But the value of the variable still refers the same object. So all the modifications inside the method actually happen on the original object.

Let’s prove it.

Example 1 : Passing a primitive type to a method

Output :

It proves that copy of the number inside the method and outside the method were different.

Example 2 : Passing a non-primitive type to a method

Output :

Fruit f was initially Sour. We pass it to the method makeSweet() where it is modified to sweet. When we access the taste field of the same fruit after the method terminates, we find the taste field set to Sweet.

It proves that argument passed to the method still referred the same original object.

3. The Proof : Objects are passed by Value

Java passes arguments by value. Let’s look at an example to prove this:

Output :

Had Java passed arguments by reference, the objects would have been exchanged i.e. names of both the students would have exchanged. But it doesn’t happen which means that Java passes arguments by value.

Let’s visualize this example with a diagram.

  • student1, student2 are references to the objects from outside the method.
  • s1, s2 and temp are local references created inside the method swap.
Java passes arguments to a method by value. The value itself is a reference value.
Java passes arguments to a method by value.