• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String pool, confused

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
Yes what Nimala said is correct and also I have compiled and got the same result
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
you are right
sorry about this question.
your help is very appreciated,
YSG
 
jafarali
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic