Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String intern puzzles [duplicate]

Tags:

java

string

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?

like image 290
Adam Sznajder Avatar asked Sep 05 '12 09:09

Adam Sznajder


People also ask

What is String intern () method used for?

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.

What are the ways to compare string?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

Is interned C#?

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.

When we create string with new () operator where is it stored?

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.


1 Answers

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).

like image 158
assylias Avatar answered Oct 24 '22 12:10

assylias