Possible Duplicate:
intern() behaving differently in Java 6 and Java 7
On this blog I found interesting String puzzles:
— Quote —
String te = "te", st = "st";
//"test".length();
String username = te + st;
username.intern();
System.out.println("String object the same is: "
+ (username == "test"));
prints under Java 7 update 7.
String object the same is: true
but uncomment the “test”.length(); line, or run with Java 6 and it prints
String object the same is: false
— EoQ —
Being honest I don’t understand why the outputs are different. Could you please explain me what’s the cause of such behaviour?
You need to assign the interned string back to username:
In which case both codes will output
true.Here is another interesting example:
prints true as well, because te and st are marked as final. So username becomes a compile time constant and is interned automatically.
EDIT
As several people pointed out your code prints false with Java 6, even when the
"test".lengthline is commented out.This is due to one of the changes introduced in Java 7:
One consequence is that the code you posted has different outputs in Java 6 and 7 (see example at the bottom of the bug report).