Java supports only to pass everything by value, and not by reference and everything means everything like- objects, arrays (which are objects in Java), primitive types (like ints and floats), etc. These all are passed by value in Java.
When passing an argument (or even multiple arguments) to a method, Java will create a copy or copies of the values inside the original variable(s) and pass that to the method as arguments - and that is why it is called pass by value. The key with pass by value is that the method will not receive the actual variable that is being passed - but just a copy of the value being stored inside the variable. So, how does this affect the code you write? Well, this is best illustrated by a simple and easy to understand example.
Example of pass by value in Java:
-------------------------------------------------------
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 "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 "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.
Lat´s take another example:
-----------------------------------------------
Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Max"); // true
public void foo(Dog d) {
d.getName().equals("Max"); // true
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}
In this example aDog.getName() will still return "Max". d is not overwritten in the function as the object reference is passed by value.
Likewise:
Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true
public void foo(Dog d) {
d.getName().equals("Max"); // true
d.setName("Fifi");
}
Java doesn´t support pass by reference to make it more secure.. Like it doesn't allow pointers explicitly
5