File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String Class intern method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Class intern method" Watch "String Class intern method" New topic

String Class intern method

Faraz Alig

Joined: Mar 14, 2010
Posts: 24

Just wanted to know what is the difference in the below line of code.

Suppose I have two objects of the type String ff and cc. In one of the code I use the below line of code

and at other place I used

Thanks in advance!!!

marc weber

Joined: Aug 31, 2004
Posts: 11343

Faraz Alig wrote:... Suppose I have two objects of the type String ff and cc...

You have two variables, but it's not clear whether you actually have two objects. That depends on how the Strings are created.

According to the API documentation...
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

For more about the string pool, see Strings Literally.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
marc weber

Joined: Aug 31, 2004
Posts: 11343

Yogesh Gnanapraksam
Ranch Hand

Joined: Dec 17, 2009
Posts: 133
Here is the output of the program posted by marc

Literals point to same object: true
New strings point to same object: false
Literal same as uninterned new: false

Literal same as interned new: true

When we create a string object using new it always creates a new object even if an identical object exists.

It is sorta covered in the JavaRanch Style Guide.
subject: String Class intern method
It's not a secret anymore!