wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings" Watch "Strings" New topic


Ram Reddy
Ranch Hand

Joined: Feb 20, 2007
Posts: 88
public class MyClass
public static void main (String args[])
String str = "SCJP";

String str2 = str.concat(""); // There is no space
// between double quotes

System.out.println(str == str2);

the out put of the above program is "true".

can any one explain me.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Rama Reddy,

As per the definition of concat(), if the passed argument's length is not zero then only the concat() method does its job and returns the reference to the new String object(after concatanation) otherwise it returns the reference to the same object. No new object is created on the String pool and as a result you got the "true" as a result of comparing two String references that refer to the same object in the string constant pool.

Hope this helps,


Prasad Shindikar
Ranch Hand

Joined: Feb 18, 2007
Posts: 114
in our case str1 and str2 still point to the same string after the concatenation.
hence a new string object is not created and thus the == operator returns true.

if the code is changed so that str2 = str1.concat(" "); // a space
then a new object is created and the == will return false.
Ram Reddy
Ranch Hand

Joined: Feb 20, 2007
Posts: 88
Thanks chandra and prasad
wood burning stoves
subject: Strings
Similar Threads
equals() and ==
Why would this print true?
String comparison
output of this program
String intern()