Thursday, 23 July 2015

Does Java pass by reference or by value?

Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those references are passed by value.


Everything is passed by value in Java.  Objects are not passed by reference in Java. Let’s be a little bit more specific here: objects are passed by reference – meaning that a reference/memory address is passed when an object is assigned to another – BUT (and this is what’s important) that reference is actually passed by value. The reference is passed by value because a copy of the reference value is created and passed into the other object.


Example of pass by value in Java

Suppose we have a method that is named “getvalue” and it expects an integer to be passed to it:
public void getvalue (int var)
{
  var = var + 5;
}
Note that the “var” variable has 5 added to it. Now, suppose that we have some code which calls the method getvalue:
public static void main(String [] args)
{
  int passing = 4;

  getvalue (passing);
 
  System.out.println("The value of passing is: " + passing);
}
Java will just create a copy of the “passing” variable and that copy is what gets passed to the getvalue method – and not the original variable stored in the “main” method. This is why whatever happens to “var” inside the getvalue method does not affect the “passing” variable inside the main method.

How does pass by value working here?

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

No comments:

Post a Comment