Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String literals are String objects!

 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jason Menard
Sheriff
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nice tip!
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic