Does Java pass by reference or by value?

Java passes by value, and not by reference. What is the difference between the two? When passing arguments to a method, Java will create a copy of the original variable and pass that to the method as an argument. This means that the method will not receive the original variable – but just a copy of it. So, how does this affect the code you write? Well, this is best illustrated by a simple and easy to understand example.

Suppose we have a method that is named “Receiving” and it expects an integer to be passed to it:

public void Receiving (int var)
{
  var = var + 2;
}

Note that the “var” variable has 2 added to it. Now, suppose that we have some code which calls the method Receiving:

public static void main(String [] args)
{
  int passing = 3;

  Receiving (passing);
 
  System.out.println("The value of passing is: " +passing);
}

In the main method, we set the variable “passing” to 3, and then pass that variable to the Receiving method, which then adds 2 to the variable passed in.

What do you think the “System.out.println” call will print out? Well, if you thought it would print out a “5″ you are wrong. It will actually print out a “3″. Why does it print out a 3 when we clearly added a 2 to the value in the Receiving method?

The reason it prints out a “3″ is because Java passes arguments by value – which means that when the call to “Receiving” is made, Java will just create a copy of the “passing” variable and that copy is what gets passed to the Receiving method – and not the original variable stored in the “main” method. This is why whatever happens to “var” inside the Receiving method does not affect the “passing” variable inside the main method.

How does pass by value work?

Java basically creates another integer variable with the value of 3, and passes that to the “Receiving” method. That is why it is called “pass by value” – because the value of 3 is what is being passed to the “Receiving” method, not a reference to the “passing” variable.

Subscribe to our newsletter for more free interview questions.


Varoon Sahgal, Author of ProgrammerInterviewon