wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings & Equality... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings & Equality..." Watch "Strings & Equality..." New topic

Strings & Equality...

Shah Chunky
Ranch Hand

Joined: Dec 27, 2000
Posts: 116
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

Shah Chunky - Sun Certified Java2 Programmer.
Scott Appleton
Ranch Hand

Joined: May 07, 2001
Posts: 195
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

Joined: Feb 14, 2001
Posts: 234
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.

sona<br />SCJP
Ravindra Mohan
Ranch Hand

Joined: Mar 16, 2001
Posts: 216
Hi Ranchers,
The reason for the behavior is outlined in the API , I am quoting it below:

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

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
I agree. Here's the link: http://aspose.com/file-tools
subject: Strings & Equality...
It's not a secret anymore!