aspose file tools*
The moose likes Beginning Java and the fly likes String literals are String objects! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String literals are String objects!" Watch "String literals are String objects!" New topic
Author

String literals are String objects!

Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
I learned a trick from an old gypsy under the light of a full moon one night. She told me that String literals are String objects and you can run methods on them. And since String literals can never be null you can never get a NullPointerException by using them! So when you want to compare a String to a literal, do it the other way around and you don't have to worry about NullPointerException.
So don't do this:
if (myString.equals("a value")) // if myString is null - NullPointerException
do this:
if ("a value".equals(myString)) // if myString is null - false


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jason Menard
Sheriff

Joined: Nov 09, 2000
Posts: 6450
Wiser words have rarely been spoken ("lift the seat first" being one of those exceptions).
Seriously this is a great habit to get into. Similarly get in the habit of doing this when you are checking equality against String constants.
Jasper Vader
Ranch Hand

Joined: Jan 10, 2003
Posts: 284
nice tip!


giddee up
Jasper Vader
Ranch Hand

Joined: Jan 10, 2003
Posts: 284
altough, it makes me wonder, as i thought String literals were placed into the String pool and not garbage collected...so not all objects are garbage collected?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Oh, sure, Thomas. Lift ideas from Java in General - Advanced and drop them into Beginner as if you invented them. :roll: Next, you'll be telling people to declare their static methods as final to prevent some newbie from confusing themselves trying to override it.


"I'm not back." - Bill Harding, Twister
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
so not all objects are garbage collected?
Any object which still has references to it is not garbage collected. String literals are in this category, thanks to the intern pool. (Unless it's implemented with a WeakHashMap and the class containing the literal is unloaded - but that's a topic for Advanced; nevermind.)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String literals are String objects!