Win a copy of Getting started with Java programming language this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is intern() method and its practicale use  RSS feed

 
ketan bhavsar
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recently come across and example of intern() method for String.
I know it just moves reference from heap memory to String pool memory.
But I want to know the detail of it. What is the reason of creation of this method.
Is it actually practically used? If yes than in which conditions. Why? how?
 
Scott Selikoff
author
Bartender
Posts: 4078
20
Eclipse IDE Flex Google Web Toolkit
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not often used since String literals are automatically interned.  I imagine it might useful in an app that uses "new String()" frequently, but wanted to make sure to tie them to strings already in the pool.  Since it's considered a better practice to test String equality with equals() rather than ==, I can't see a lot of use for this though, especially with memory being so abundant these days.  I imagine applications that manage huge numbers of String values in memory might want to use it, but it wouldn't be common.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 36171
439
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also note that intern isn't on the cert exam
 
Jacky Stark
Ranch Hand
Posts: 34
1
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ketan, this might be a bit off topic but it will give you a simple conclusion.

Intern pool is exactly same as Thread pool or more simpler , cache in your browser. You save a particular URL in your cache or regularly visited sites will be in cache such that the next time you visit the same site the browser can easily pick from the cache itself. Similarly JVM creates a pool of Strings which are declared and initialised with new operator such that it can pick from the pool when you next time refer to the same string literal.
 
Roel De Nijs
Sheriff
Posts: 10900
155
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ketan bhavsar wrote:Is it actually practically used? If yes than in which conditions. Why? how?

You should definitely read this excellent article! A must-read for every Java developer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!