Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String pool, confused 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 pool, confused" Watch "String pool, confused" New topic
Author

String pool, confused

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I have small programm as following:
public class test{
public static void main (String ags[])
{
String s1 = "ABC";
String s2 = new String ("ABC");
if (s1.equals(s2))
System.out.println("Yes");
else
System.out.println("NO");
}
}
pls correct me if I am wrong, si is in String pool and s2 is in heap. because s1 and s2 located in diffrent place (heap and String pool), so it should print out "NO".
thank you for help,
ysg
Nirmala
Ranch Hand

Joined: Jun 28, 2000
Posts: 93
Hi Ysg,
Yes you are right.
'equals' method will do deep comparison ,means that 'equals' method will compare the contents character by character.
'==' comparision means 'shallow' comparison.
Here is the modification of your program,please look at it compile & run see .
public class test{
public static void main (String ags[])
{
String s1 = "ABC";
String s2 = new String ("ABC");
if (s1.equals(s2))
System.out.println("from equals:Yes");
else
System.out.println("from equals:NO");
if (s1==s2)
System.out.println(" from == :Yes");
else
System.out.println("from == :NO");

}
}

So this will print 'from equals:Yes' and 'from == :NO'.
Hope I answered yr question,Am I?.
Thanks
Nirmala
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
NO, sorry, you misunderstand my point or my statement was not clear,
in my question, the right answer is "Yes", but I thought it is supposed to be "NO". I
again, s1 is in string pool and s2 is in heap, so print out should be "NO" rather than "Yes", I have run this programm and got "NO", can you tell me why?
thanks a lot,
ysg
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Yes what Nimala said is correct and also I have compiled and got the same result
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
you are right
sorry about this question.
your help is very appreciated,
YSG
jafarali
Ranch Hand

Joined: Jul 15, 2000
Posts: 37

Ysg,
Actully when you use s1.equls(s2)=> with String it compares the content of the String not the reference which is equal in your case. But when you use == it will compare the reference value which is different
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String pool, confused