File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings" Watch "Strings" New topic
Author

Strings

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,

Regards,
cmbhatt


cmbhatt
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings