1.

Java works as “pass by value” or “pass by reference” phenomenon?

Answer»

Java always WORKS as a “pass by value”. There is nothing called a “pass by reference” in Java. HOWEVER, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get REFLECTED the original object before it was passed to the method as the reference points to another location.

For example:

class InterviewBitTest{ int num; InterviewBitTest(int x){ num = x; } InterviewBitTest(){ num = 0; }}class DRIVER { public static void main(String[] args) { //create a reference InterviewBitTest ibTestObj = new InterviewBitTest(20); //Pass the reference to updateObject Method updateObject(ibTestObj); //After the updateObject is EXECUTED, check for the value of num in the object. System.out.println(ibTestObj.num); } public static void updateObject(InterviewBitTest ibObj) { // Point the object to new reference ibObj = new InterviewBitTest(); // Update the value ibObj.num = 50; }}Output:20
  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

For example:

class InterviewBitTest{ int num; InterviewBitTest(int x){  num = x;  } InterviewBitTest(){  num = 0;  }}class Driver{ public static void main(String[] args) { //create a reference InterviewBitTest ibTestObj = new InterviewBitTest(20); //Pass the reference to updateObject Method updateObject(ibTestObj); //After the updateObject is executed, check for the value of num in the object. System.out.println(ibTestObj.num); } public static void updateObject(InterviewBitTest ibObj) { // no changes are made to point the ibObj to new location // Update the value of num ibObj.num = 50; }}Output:50


Discussion

No Comment Found