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 string related question 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 "string related question" Watch "string related question" New topic
Author

string related question

Amisha Shah
Ranch Hand

Joined: Mar 03, 2006
Posts: 33
program:
class strc
{
public static void main(String args[])
{
String s1="amisha";
String s2="amisha";
if(s1==s2)
{
System.out.println("same");
}
else
{
System.out.println("different");
}
}
}

in java string is an object. so when i evaluate if(s1==s2) , the test condition is evaluated as false. because both string object refers to different memory location even if contents are same. so output of this program should be different but when i run this progarm , output is same.

please tell me how this works ?


Amisha Shah.<br />SCJP 1.4
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
When you create a String literal it automatically goes into the String pool. Whenever you create another reference to the same literal it refers to the String already in the pool. A new String object is not created.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See Corey McGlone's article, "Strings, Literally."


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288


java j2ee job interview questions with answers | Learn the core concepts and the key areas
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: string related question