Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
null pointer exception
Joined: Oct 26, 2008
Oct 30, 2008 14:46:00
Without line 6 this code throws nullpointer exception.
but with it ,prints null.
How come? please explain
public static void main(String args)
s = s + ""; //line 6
String s1 = s.toLowerCase();
SCJP 5 , SCWCD 5
Joined: Oct 27, 2005
Oct 30, 2008 14:53:00
Every static or instance field gets an initial value. For numbers that's 0, for booleans false, and for objects
Since line 6 is the only assignment to static field s, without that line s will remain null. When you then try to call a method on it (line 8) - BOOM!
Now on line 6 you assign something to s. You are using the old value of s for that though, so the result will be
null + ""
Because of this concatenation, the null is converted to string literal "null" and then concatenated with the empty string - leading to the string "null".
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions
How To Answer Questions
Joined: Aug 31, 2004
Oct 30, 2008 15:10:00
For details (and future reference), see
JLS - 15.18.1 String Concatenation Operator +
If an operand of type String is null, then the string "null" is used instead of that operand.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award."
With a little knowledge, a
cast iron skillet
is non-stick and lasts a lifetime.
subject: null pointer exception
ask help about gc!!!
working with null...
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014