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
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.
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
Joined: Jan 30, 2000
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.)