-2
    Integer i = new Integer(10);
    Integer j =10;
    System.out.println(i==j); // false

    String a1 = new String("abc");
    String a2 = "abc";
    System.out.println(a1==a2); // false

But to make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool." When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.) So String literals are immutable. So, both a1 and a2 will have two reference pointing to same memory location then why "==" doesn't return true?

Vineet Raj
  • 85
  • 1
  • 1
  • 7
  • 2
    It might help your [Difference among several ways of creating string](http://stackoverflow.com/questions/23544752/difference-among-several-ways-of-creating-string?answertab=votes#tab-top) – Braj May 25 '14 at 08:25
  • 2
    See http://stackoverflow.com/questions/14150628/string-constant-pool-java?rq=1 – Alexis C. May 25 '14 at 08:26

1 Answers1

2

This happens because a1 is not a literal. It's a new String that you created on the heap, outside of the string pool. The constructor that you used actually copied the String to a new location. However, a2 is in the string pool.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • just one more query about this: --String str1="sairam"; String str2=str1; System.out.println(str1==str2); System.out.println(""+ str1==str2); System.out.println(""+str1==str2+""); Why the output is displaying (true, false, false). – Vineet Raj May 26 '14 at 17:09
  • because using `+` creates a new `String`. Sorry, I'm not sure why you wouldn't expect the output that you're getting from that. – Dawood ibn Kareem May 26 '14 at 18:25