0

Possible Duplicate:
How do I compare strings in Java?

I am new to Java and I have difficulties in understanding String comparison. Can anyone explain the differences between the following scenarios?

Scenario 1 :

String a = "abc";    
String b = "abc";

When I run the if(a == b) it returns true.

Scenario 2 :

String a = new String("abc");    
String b = new String("abc");

and run if(a == b) then it returns false.

What is the difference?

Community
  • 1
  • 1
user987654
  • 41
  • 1
  • 6

7 Answers7

4

== operator compares the references of two objects in memory. If they point to the same location then it returns true.String object in java are Immutable, so when you create Strings like in scenario1 then it didn't create new string. It just points the second string to the memory location of first string.

However, .equals() method compares the content of the String. When strings has same value then this method returns true.

So, in general it is recommended to use equals() method instead of ==.

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
4

It's because of Java String constant memory pool. Same valued literals are stored once.

String a = "abc";
String b = "abc";
// Now there is 1 string ("abc") and 2 references pointing to it.

String a = new String("abc");
String b = new String("abc");
// Now you have 2 string instances and 2 references.
Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • 1
    yes downvoter, what is the issue? – Juvanis Dec 27 '12 at 14:58
  • You may have one instance, it depends on the runtime and possibly even the compiler. Interning wasn't mentioned, as it is in this Q/A: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java. And I did warn before downvoting. – Maarten Bodewes Dec 27 '12 at 15:19
1

Scenario 1 returns true because of a compiler optimization.

In general you should use equals() instead of == to compare strings.

miniBill
  • 1,743
  • 17
  • 41
1

In Java you need to use like this if(str.equals(str2)) which compares actual value of string rather than references.

Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107
1

Case1:

 String a = "abc";
    String b = "abc";
    if(a == b)

In this case abc is cached in String constant pool thus a new string is not created String b = "abc"; b just refers to the string created by a it returns true as a and b both point to the same Object in the memory.

Case2:

String a = new String("abc");
String b = new String("abc");
and run if(a == b) then it returns false.

Here a two Strings are created and == operator just checks if two references point to the same reference, which it doesnt in this case thus it returns false

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

The reason is that the String literal "abc" will be turned into a global String instance for all its ocurrences, it will be the same String instance therefore you can be sure that "abc" == "abc". It is possible for the compiler to do that because String instances are immutable. However, if you explicitly allocate the String they will be two different instances and they will also be different to the String instance implicitly created by the compiler i.e. new String("abc") != new String("abc") and "abc" != new String("abc").

Another good example to understand what the compiler is doing is to look at this code:

"abc".contains("a");

you see that the literal behaves like an instance of a String type. You may exploit this to minimize programming errors e.g.

// this is OK and the condition will evaluate to false
String myStringValue = null;
if ("abc".equals(myStringValue)) { // false

whereas this code results in NPE:

// this will produce a NPE    
String myStringValue = null;
if (myStringValue.equals("abc")) { // NPE 
SkyWalker
  • 13,729
  • 18
  • 91
  • 187
  • 1
    Most of the time when I perform string comparison I coded the program to *expect two string instances*. I would go as far as checking for `null` *separately* if my method would allow a `null` value as argument. In such cases I would *want* the application to throw an NPE, instead of happily running along within a (possibly) undefined state. – Maarten Bodewes Dec 27 '12 at 15:02
  • One problem, many solutions, pick your color and be happy with it. I use the approach I explained to elegantly minimize programming errors. – SkyWalker Dec 27 '12 at 15:09
  • I pick a color each time I run into this particular issue. Just shuffling exceptions under the table each time one can be encountered is not a solution though, and I at least want the reader to be aware of this, hence the comment. – Maarten Bodewes Dec 27 '12 at 15:17
  • If you call this to shuffle exceptions it only reveals your ignorance of the language and you coding style more prone to errors and unnecessarily overly defensive. It is your bad style but I dont come to bug you about it. – SkyWalker Dec 27 '12 at 15:33
1

Two ways of creating string are 1) String s ="hello"; No. of string literal = 1 i.e. "hello" - No. of String objects on heap = 0

2) String s= new String("hello"); - No. of string literals =1 and No. of string objects =1

Java maintains a string pool of "LITERALS" and objects are going to stay on heap.

Advantage of string pooling: 1) Reduced memory usage*(PermGenSpace Issue) 2) Faster Comparision i.e == comparision 3) Faster lookup Disadvantages: 1) Overhead of maintaining pool

How to pool String objects? Use Intern() on a string to add it to the pool. Downside of interning: 1) You may forget to intern some strings and compare them by == leading to unexpected results.

Srujan Kumar Gulla
  • 5,721
  • 9
  • 48
  • 78