-1

Following code:

    String a = new String("aaa");
    String a2 = new String("aaa");
    System.out.println(a == a2);

    String b = "bbb";
    String b2 = "bbb";
    System.out.println(b == b2);

Produces following output:

false
true

Why there is difference in output for comparision a==a2 and b==b2 depending from type of String creation ?

user109447
  • 1,069
  • 1
  • 10
  • 20
  • [What is the difference between "text" and new String("text")?](http://stackoverflow.com/q/3052442) – Tom Dec 15 '15 at 00:04

1 Answers1

-1

When you declare a and a2 you explicitly create new (different) Strings. The use of the constructor causes a copy to be made. Hence == fails as a and a2 point to different values.

When you declare b and b2, b2 can re-use the same string from the pool. Hence they actually point to the same value and == returns true.

Take a look here or here for a detailed answer.

Community
  • 1
  • 1
dave
  • 11,641
  • 5
  • 47
  • 65