Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings & Equality...

 
Shah Chunky
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Scott Appleton
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sona gold
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the compiler is smart enough to know that the concatation is trying to create a string which is no different from already existing string and hence does not create a new string.
 
Ravindra Mohan
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic