+ 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); } }
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
+ 8
but sometimes it says the answer is 31
+ 8
how so?
+ 7
33
+ 7
thanks qwerty
+ 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");".
+ 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);
}
}
+ 1
33