This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Hello all... Strings & Equality... Can someone tell me why the below Cases prints true. Doesn't the below code create a new String Object when we concat String str with (""). // Case 1:- String str = "SCJP"; String str2 = str.concat(""); System.out.println(str == str2); // Prints True. (1) System.out.println("java".toString()=="java"); // True (2) // End of Code Doesn't line 2 create a new String Object when using toString() which returns String. Thanks.
I believe that the compiler recognizes that concatenating an empty string "" to a literal does not change the value of the literal. When assigning Strings to identical literals in the pool, the compiler optimizes by pointing both String objects to the same literal, thereby making them equivalent not only in value but also in reference. So it creates a new String variable (str2) but rather than creating a new String object, it just refers it to the same object already created by the previous line of code.
Hi Ranchers, The reason for the behavior is outlined in the API , I am quoting it below:
concat public String concat(String str) Concatenates the specified string to the end of this string. If the length of the argument string is 0 , then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.
Hope it is clear now. However, if you try to do something like
the result will as expected print "false" as the concat() method in this case return a new string. Please revert in case you have any difficulty on this. Ravindra Mohan