+ 9

could someone help me and explain the difference in the result between the two codes?

It would be something like: when I use String to instantiate it passes the reference and when I do not use it, it passes the value. am I sure? Code 1: public class Program { public static void main(String[] args) { A a = new A("1"); A c = a; a.a1 = new String("3"); System.out.print(a.a1); System.out.println(c.a1); } } class A{ public String a1; public A(String a1){ this.a1=a1; } } //Result: 33 Code 2: public class Program2{ public static void main(String[] args) { A a = new A("1"); A c = a; a = new A("3"); System.out.print(a.a1); System.out.print(c.a1); } } class A{ public String a1; public A(String a1){ this.a1=a1; } } //Result:31

17th Oct 2017, 5:09 PM
Malkon F
Malkon F - avatar
3 odpowiedzi
+ 5
When you do - a.a1 = new String("3"); - you're changing the field a1 in the object a, which is public. And in - a = new A("3"); - you're creating a new object and using a to refer to that new object you just created.
17th Oct 2017, 5:15 PM
Chriptus13
Chriptus13 - avatar
+ 6
I understand perfectly well! In the first code it changes the value a1 that is public and used both by a and by c, so the result of a and c is the same. In the second code c remains with the value of the first object created.Thanks a lot!
17th Oct 2017, 5:28 PM
Malkon F
Malkon F - avatar
+ 4
Yes because you created a new object for the variable a and didn't change c so c is still refering the old object.
17th Oct 2017, 5:27 PM
Chriptus13
Chriptus13 - avatar