+ 1
Having a hard time getting the logic. Can anyone please explain?
Found this question in a quiz What is the output of this code? class A { int x; } class B { public static void main(String[] args) { A a1, a2, a3; a1 = a2 = a3 = new A(); a1.x = 2; System.out.print(a1.x); a2.x = 3; a3.x = 4; if (a1.x == a3.x) System.out.print(a2.x); else System.out.print(0); } } Answer is 24!
2 ответов
+ 5
Don't read the output as Twenty-four, but Two and then Four output on the same line. A is an object and a1 = a2 = a3 = new A(); will make all 3 references (a1, a2, a3) point to the exact same object. So any change made from any one of those objects will also change the other two.
a1.x == a3.x will always be true as a1 and a3 point to the same object so the value of x is always the same across them no matter which reference was used to access or change x.
+ 1
Thanks a lot. That helped