+ 6

What is the correct answer to this quiz question?

public class A { String a1; public A (String a1){ this.a1 = a1; } } class MyClass { public static void main (String [] arguments){ A a = new A ("1"); A c = a; a.a1 = new String ("3"); System.out.print (a.a1); System.out.print (c.a1); } }

14th Oct 2017, 7:27 AM
David Akhihiero
David Akhihiero - avatar
8 Answers
+ 7
public class A { String a1; public A (String a1){ this.a1 = a1; } } class MyClass { public static void main (String [] arguments){ A a = new A ("1"); A c = a; a.a1 = new String ("3"); System.out.print (a.a1); System.out.print (c.a1); } } Answer: 33 The other one: public class A { String a1; public A (String a1){ this.a1 = a1; } } class MyClass { public static void main (String [] arguments){ A a = new A ("1"); A c = a; a = new A("3"); System.out.print (a.a1); System.out.print (c.a1); } } Answer: 31
14th Oct 2017, 7:38 AM
qwerty
qwerty - avatar
+ 8
but sometimes it says the answer is 31
14th Oct 2017, 7:30 AM
David Akhihiero
David Akhihiero - avatar
+ 8
how so?
14th Oct 2017, 7:31 AM
David Akhihiero
David Akhihiero - avatar
+ 7
33
14th Oct 2017, 7:29 AM
qwerty
qwerty - avatar
+ 7
thanks qwerty
14th Oct 2017, 11:02 AM
David Akhihiero
David Akhihiero - avatar
+ 5
@Yerucham That's a different challenge question. In this one it's "a.a1 = new String("3");" and the other one is "a = new A("3");".
14th Oct 2017, 7:31 AM
qwerty
qwerty - avatar
+ 2
the reason is when A c = a, it makes c as a reference to a. so if you ask for c.a1 it returns the value in the reference. object c will have its own a1 value if you initialize it to the original class like A c = new A("1"); for example the following code as well, will return 31. public class A { String a1; public A (String a1){ this.a1 = a1; } } class MyClass { public static void main (String [] arguments){ A a = new A ("1"); A c = new A("1"); a.a1 = new String ("3"); System.out.print (a.a1); System.out.print (c.a1); } }
14th Oct 2017, 10:53 AM
M. Thenuwara
+ 1
33
14th Oct 2017, 3:26 PM
Sharad M
Sharad M - avatar