0

I know that we shouldn't compare Strings with == and its better to use equals.
For so far I learned this should all be false.
So why does the first method return true?

private String ab = "AB";
private String ab2 = "A" + "B";
private String a = "A";
private String b = "B";
private String ab3 = a + b;

public void test () {
    System.out.println("ab == ab2" + ab==ab2);
    System.out.println("ab == ab3" + ab==ab3);
    System.out.println("ab == a+b" + ab==(a+b));
}
chillworld
  • 4,207
  • 3
  • 23
  • 50

2 Answers2

5

Because the concatenation of literal Strings are compiled into a single String, which will also be interned in the String pool. This code:

private String ab2 = "A" + "B";

is compiled to

private String ab2 = "AB";

ab and ab2 point to the same literal String "AB", thus they're ==s.

Still, you should not trust comparison of Strings with ==, you should always compare their equality using equals method.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

It is called String interning:

http://en.wikipedia.org/wiki/String_interning

To summarize, since strings are immutable in Java, JVM optimizes by creating only one object for two string literals that are equal. Therefore, comparison returns true.

Selcuk
  • 57,004
  • 12
  • 102
  • 110