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?
intern() The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
The C# Intern() method is used to retrieve reference to the specified String. It goes to intern pool (memory area) to search for a string equal to the specified String. If such a string exists, its reference in the intern pool is returned.
26) In which memory a String is stored, when we create a string using new operator? Explanation: When a String is created using a new operator, it always created in the heap memory.
You need to assign the interned string back to username:
String username = te + st;
username = username.intern();
In which case both codes will output true
.
Here is another interesting example:
final String te = "te", st = "st";
"test".length();
String username = (te + st);
System.out.println("String object the same is: " + (username == "test"));
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".length
line is commented out.
This is due to one of the changes introduced in Java 7:
in JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With