Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String object and string literal

 
Joy Vergis
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between String object and String literal.

Example:




What is the difference between the line no1 and 2. Which one is better. When to use either. Does declaring a Sttring name as final has helps in selecting 1 or 2.


Please help.


Thanks,
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JVM maintains a pool of Strings, so that frequently used values can be reused instead of being instantiated all over again. In the following code, the two string variables refer to the same String instance:

Strings a and b are both literals. Their values are assigned explicitly rather than through the use of a constructor. If you assign a String using the new keyword, that value does not get added to the String pool. A new String instance is always created. It gets created even if that String value already exists in the pool and could have been used instead.

String c is NOT the same instance as Strings a and b.

It's almost always preferable to use literals instead of the String constructor.
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at StringsLiterally
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic