Java is Pass-By-Value and Objects Passed as Parameters

Java is Pass-By-Value

The Java language (unlike C++) uses pass-by-value for all assignment operations.

  • To visualize this with primitives , consider the following:
  • The value of x is copied and passed to y:
  • If x is later modified (for example, x=5;) , the value of y remains unchanged.

The Java languages uses pass-by-value to all assignment operations. This means that the argument on the right side of the equal sign is evaluated, and the value of the argument is assigned to the left side of the equal sign.

For Java primitives, this is straightforward. Java does not pass a reference to a primitive ( such as a integer), but rather a copy of the value.


Pass-By-Value for Object References

For Java objects, the value of the right side of an argument is a reference to memory that stores a Java object.




  • The reference is some address in memory.

  • After the assignment , the value of y is same as the value of x: a reference to the same Employee object.
For Java objects, the value of an object reference is the memory pointer to the instance of the Employee object created.

When you assign the value of x to y, you are not creating a new Employee object, but rather a copy of the value of the reference.

Objects Passed as Parameters

  • Whenever a new object is created , a new reference is created :



  • The value of x is unchanged as a result of the method call foo:


In the first line of code, a new object (Employee) is created and the reference to that object is assigned to the variable x.

In the second line of code, the value of that reference is passed to a method called foo.

When the foo method is called (Employee e)holds a reference to the Employee object, x.
In the next line, the value of e is now a new Employee object, virtue of the call to the constructor.

The reference to the x object is replaced by a reference to a new object. The  x object remains unchanged.

If the code in the foo method is written differently, like this:

public void foo( Employee e){

e.setSalary(1_000_000.00):

}

Then the referenced object that the setSalary method is being called on is the object referenced by x, and after the foo method returns , the object x is modified.

Note: The memory locations 42 and 99 are simply for illustrative purpose!.

About Codingwelove

Codingwelove
Recommended Posts × +

0 comments:

Post a Comment