2

Possible Duplicate:
Difference Between Equals and ==
In JDK 1.6, can String equals operation can be replaced with ==?
How do I compare strings in Java?

While playing around with Java-Strings, i did not expect the following results:

public class Sandbox {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";

        System.out.println(a == b);             //true        Why?, a and b both are seperate Objects
        System.out.println(a == "hello");       //true        Why?
        System.out.println(a == new String(b)); //false       As expected
    }
}

I expected all to be false, since "==" compares references. Why this outcome?

When i change String b = "world", System.out.println(a == b); returns false. It seems as if the content of the String-Object is beeing compared.

Since Java 7 can compare Strings in switch-case-Statements, i thought it might have something to to with the Java-Version. But as described here, the equals-Methode is invoked when comparing Strings within a Switch-Case.

Community
  • 1
  • 1
  • Please read [this](http://stackoverflow.com/questions/971954/difference-between-equals-and). – mre Apr 12 '12 at 11:42
  • In summary, some strings are interned (i.e. cached) and refer to the same object, which explains why == can work. But you can't rely on that mechanism and should use equals. – assylias Apr 12 '12 at 11:45
  • Bottom line is, as string is still and object, so in the vast majority of cases you should be using the `equals` method. – Nick Holt Apr 12 '12 at 11:49

2 Answers2

3

Java has always (from version 1.0) interned string literals. This means that constant strings are added to a pool and duplicates reference the same object.

final String a = "hello";
final String b = "hell";
System.out.println(a == b + 'o');

This prints true as the compiler can inline and simplify the expression b + 'o' to be the same as "hello".

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.

Anonymous
  • 18,162
  • 2
  • 41
  • 64
  • 3
    It's called *string interning* and is common in most modern languages - http://en.wikipedia.org/wiki/String_interning – Nick Holt Apr 12 '12 at 11:47
  • Yes, it was already explained in other comments. _Some trickery_ could have been to vague. – Anonymous Apr 12 '12 at 11:48