Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in String...Plz Help Me

 
Thangaraj Selvamani
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MWC114 {
public static void main(String[] s) {
String s1 = new String("ABCDEFG"), s2 = new String("EFGHIJ");
String s3 = s1.substring(4,7), s4 = s2.substring(0,3);
System.out.println(s3 == s4);
String a="Hai";
String b="Hai";
System.out.println(a == b);
}

}


Why First System.out.println Shows False...
Even though Both s3 and s4 refers to same value "EFG"

[ October 15, 2008: Message edited by: Thangaraj Raj ]
 
Rekha Srinath
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its because s3 and s4 are two different reference variables. So, even though their contents are the same, when you use == operator, it returns false.

Whereas, in the second println statement, the String constant pool comes into picture. If the JVM finds the same string in the pool, instead of creating a new object, it will make the new reference point to the already existing String.

So, since "Hai" is already present in the pool (which was created through String a="Hai"), JVM just points the reference b to it, and hence it returns true when comparing a and b using == operator.
 
subhasish nag
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s3 and s4 are reffrering two different objects.== checks wheather bothe references two same object or not.If you use equals() method then the result will be true.
And in a==b it returns true as ure creating String without new operator. So at the the time of creating object referenced by a stored in String pool and b references to the same object.If you use new operator for creating String then it will return false.
 
Thangaraj Selvamani
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic