InterviewSolution
Saved Bookmarks
| 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:
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
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 |
|