Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Class intern method

 
Faraz Alig
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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!!!
Faraz



 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Yogesh Gnanapraksam
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks
Yogi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic