Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null pointer exception

 
priya rishi
Ranch Hand
Posts: 119
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
System.out.println(s);
String s1 = s.toLowerCase();
System.out.println(s1);
}
}
 
Rob Spoor
Sheriff
Pie
Posts: 20380
45
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic