This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes String object and string literal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String object and string literal" Watch "String object and string literal" New topic
Author

String object and string literal

Joy Vergis
Ranch Hand

Joined: Sep 14, 2009
Posts: 45
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

Joined: Mar 12, 2011
Posts: 808
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

Joined: Jul 18, 2011
Posts: 287
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Have a look at StringsLiterally
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String object and string literal