Scanner class Methods in Java

Passing Arguments : Pass by Reference

Pass By Reference


When we pass an object reference variable as an argument then a copy of reference to the original object is passed to the matching parameter of the method. Unlike pass by value, a copy of the address or reference to the original object is passed , not a copy of original object. The argument passed and the matching parameter both refer to the same object because they both contain the address of the original object. That is why in pass by reference the modifications or change in the instance variable of an object are reflected back to the original object in the calling methods as well. To understand the difference see pass by value also.

In pass by reference, we pass objects to methods as arguments. These objects contains the reference of the actual variable. It does not create any copy of actual variable or value instead it only generates the copy of reference of actual variable. So, when we modify the variable using object, the change reflects in the actual value of variable.

Example: Lets understand pass by reference with an example.

Write a program to show the use of pass by reference while passing arguments or parameters.

Write a program to show the use of pass by reference while passing arguments or parameters.
Example of Pass By Reference



In the above program,
  1. We have a Cookie class in which we first declared a variable named "numOfCookies" to count the number of cookies. We initialized this variable in the constructor of class.Then we created a method "increase()". This method take the object of Cookie class as an argument and it increments the numOfCookies variable by 1000.
  2. The "PassByReference" is the main class which contains main method.In the main method,we have created the object of Cookie class using new Keyword. Then we print the value of variable before increment. 
  3. In line 8, we are incrementing the number of cookies by using object to invoke the increase() method which takes obj object as an argument.
  4. After increment the original value of noOfCookies is changed.Because the obj contains the copy of reference of object and the modification reflects in original of variable.
Output:

pass by reference


 Happy Coding!

Comments