Snippet1
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a.j);
xyz(a);
System.out.println(a.j);
}
private static void xyz(A a) {
a = new A(); //watch this line
a.j=20;
}
}
class A {
public int j = 10;
}
Output:
10
10
Snippet2
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a.j);
xyz(a);
System.out.println(a.j);
}
private static void xyz(A a) {
//a = new A(); //commented
a.j=20;
}
}
class A {
public int j = 10;
}
Output:
10
20
In snippet 2, did you notice that the updated value from the method xyz is printed in the main method? In snippet 1, the updated value from the xyz method is not reflected in the main method and hence the updated value is not printed. There are reasons behind this behavior.
In the main method of snippet 1, an object A is created at memory location say “XYZ”. The memory location of the object is passed as parameter to method xyz. In xyz method, the statement a= new A(), creates a new A object at a different memory location say “PQR”. The value of the variable “j” in the object at memory location “PQR” is then updated to 20. When the method xyz returns, the main method still refers to the “XYZ” memory location and hence prints the original value of 10 and not 20.
In the main method of snippet 2, as in snippet 1, the object A is created at memory location “XYZ”. The memory location of the object is passed as parameter to method xyz. In xyz method, the value of the variable “j” in the object at memory location “XYZ” is then updated to 20. When the method xyz returns, the main method still refers to the “XYZ” memory location and hence prints the updated value of 20.
Try making the variable “a” as class level variable and static in nature, you will find the difference. You should be able to identify the difference.
No comments:
Post a Comment