This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes null pointer exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null pointer exception" Watch "null pointer exception" New topic

null pointer exception

priya rishi
Ranch Hand

Joined: Oct 26, 2008
Posts: 119
Without line 6 this code throws nullpointer exception.
but with it ,prints null.
How come? please explain

class nullDemo
static String s;
public static void main(String args[])
s = s + ""; //line 6
String s1 = s.toLowerCase();

Rob Spoor

Joined: Oct 27, 2005
Posts: 19651

Every static or instance field gets an initial value. For numbers that's 0, for booleans false, and for objects null.

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! NullPointerException.

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

Because of this concatenation, the null is converted to string literal "null" and then concatenated with the empty string - leading to the string "null".

How To Ask Questions How To Answer Questions
marc weber

Joined: Aug 31, 2004
Posts: 11343

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." ~Joe Strummer
jQuery in Action, 2nd edition
subject: null pointer exception
Similar Threads
GC Doubt
GC Problem
ask help about gc!!!
Garbage collector
working with null...