Forums Register Login

null pointer exception

+Pie Number of slices to send: Send
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);
}
}
+Pie Number of slices to send: Send
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".
+Pie Number of slices to send: Send
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'm sure glad that he's gone. Now I can read this tiny ad in peace!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 786 times.
Similar Threads
Unable to detect null behaviour
what will it do?
pRINTING AN OBJECT WITH NULL REFERENCE
pRINTING AN OBJECT WITH NULL REFERENCE
Exception
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 12:55:04.