Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String manipulation  RSS feed

 
lokesh kumar
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,
will any one tell me why this piece of code does not work...
String a = new String("trial text");
String b = new String("trial text");
if(a==b)
System.out.println("TRUE "+ "A :" + a + " " + "B :" + b);
else
System.out.println("FALSE " + "A :" + a + " " + "B :" + b);

This piece of code comes to the else part always....why ?
I know there is equals(object) & equalsIgnoreCase(String) methods in String class which does the job fine.....
will any one describe me why this piece of code always goes to else part always.....
but if the new key word is removed this works fine... during teh declaration of the String....
thank U
Regards,
Lokesh
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, you've stumbled on the great mysteries of Java's String Pool
Remember, "comparing Strings with '==' is like running with scissors." (As another bartender here has previously commented.) The '==' operator tests objects for physical equality (is it at the same spot in memory), not logical equality (do these objects mean the same thing?).
So this will always hit the else:

Note that this is what you are doing; by using the "new" keyword, you are explicitly creating separate objects in memory.
To complicate matters, Java will put literal Strings into a special "String Pool." This is a Set of String literals; there are no duplicates. So, everywhere you have a literal "This is a String" in your code will reference the same object in the pool. Since an object is itself, it will always == itself. The following code always returns true:

Note that, as in the first example, you can force the creation of new objects and have this always return false:
 
Amol Takate
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lokesh ,

When you say
String a = new String("a") ;
you are always creating a new String object.
But when you say String a = "a"
you will not always create a object .
Because , JVM internally maintains a pool of strings.
so if there is already a string object with content "a" then
instead of creating a new string object , your exisiting object in a pool will be used.
(a == b) operator is used to test whether two refrences are pointing to same object or not.
so when you create a string using a second method , it wil return a true as both refresnces will point two same string object.
But when you create a string using "new" operator , JVM will neccessarily create a new string object and so there refrences will point to two different objects and == will return false .
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!