I am new to Java and I have some questions in mind regarding object assignment. For instance,
Test t1 = new Test();
Test t2 = t1;
t1.i=1;
Assuming variable i
is defined inside Test class, am I right to assume both t1 and t2 point to the same object where the modification t1.i=1
affects both t1
and t2
? Actually I tested it out and seems like I was right. However when I try the same thing on String
, the modification happens only on one side where the other side is unaffected. What is the reason behind this?
Edit: The case I tried with String.
String s1 = "0";
String s2 = s1;
s1 = "1";
System.out.println(s1);
System.out.println(s2);
I realise my mistake by testing the cases on String since it is immutable. The situation where I thought s1="1"
modify the string is in fact returning the reference of "1" to the s1. Nevertheless, my question remains. Does Test t2 = t1;
cause both t2 and t1 point to the same object or each now have their own objects? Does this situation applies on all objects on Java?
You are right, but Strings are a special case; they are immutable and act like primitives in this case.
@newacct
I quote http://docs.oracle.com/javase/tutorial/java/data/strings.html :
Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
This is what makes strings a special case. If you don't know this, you might expect the methods discussed in the quote not to return new strings, wich would lead to unexpected results.
@user1238193
Considering your following question: "Does Test t2 = t1; cause both t2 and t1 point to the same object or each now have their own objects? Does this situation applies on all objects on Java?"
t1 and t2 will point to the same object. This is true for any java object (immutable objects included)