PDA

View Full Version : Java: subtle issue with String comparison



alexmoca
April 18th, 2011, 02:45 AM
SOURCE:



String a = "a";
String b = "a";
String c = new String("a");
String e = new String("a");

System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == e);
System.out.println(c == e);
OUTPUT:



true <<<<< WHY?
false
false
false
Question: Why?

So c and e are instantiated with the new operator. Therefore, they refer to different memory addresses and afaik this is true for all objects instantiated with this operator. But what is the process behind creating the Strings a and b? I was a bit surprised to find that a == b returned true.

Some Penguin
April 18th, 2011, 02:48 AM
'Interning'.

See http://en.wikipedia.org/wiki/String_interning and http://javatechniques.com/public/java/docs/basics/string-equality.html