System.out.println( str1); System.out.println( str3); } } As String class is immutable, a new object is created when the content of the String instance changes. But in the above code snippet, str1 concatenate with str2. The result string is assigned backed to str1(same intance name). Will this str1 be a new object or still be the original str1 which contains "str1"? Thanks
hi roger u must understand that assignment has lower precision so firstly str1 and str2 holding initial values get concated then the result is trying to store values in str1. as string pool does not hold string object like "str1str2" so new object is created and str1 starts pointing to it. rgds vishal
After the operations are performed, str1 points to a NEW concatinated String, "str1str2". Your code verifies this. Before the concat() operation is performed, str1 and str3 both point to the same String. If the concat() operation had changed the data within the String, str1 and str3 would still point to the same String after the concat() command. When you run the code, however, you will see that it does not. str1 points to the new concatinated String, and str3 still points to the original String.
Originally posted by vishal avad: as string pool does not hold string object like "str1str2" so new object is created and str1 starts pointing to it.
Vishal, even if the String pool had a String "str1str2" a new String would have been created because of the way String objects are concatenated. The concat method returns a new String object (created with new). And Roger, you must understand the difference between a reference to a String object (here str1, str2 and str3) and the actual String object. str1 is not the instance name of the String referenced by str1, BUT the name of the variable that references it. It's important to make that distinction. Reference variables are in fact pointers to objects. When you create a new object (with new), there is only one instance of that object, but you may create mutliple reference to that object using reference variables. It is the case here with str1 and str3 which both reference the same String instance "str1" ! That does not mean that there are two instances of "str1" ! HIH ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform [This message has been edited by Valentin Crettaz (edited November 30, 2001).]