Forums Register Login

When does a NullPointerException occurs?

+Pie Number of slices to send: Send
1 String s = null;
2 if ( s != null & s.length() > 0)
3 System.out.println("s != null & s.length() > 0");
4 if ( s != null && s.length() > 0)
5 System.out.println("s != null & s.length() > 0");
6 if ( s != null | | s.length() > 0)
7 System.out.println("s != null & s.length() > 0");
8 if ( s != null | s.length() > 0)
9 System.out.println("s != null | s.length() > 0");
Why line 2,6,8 give the NullPointerException while line 4 not?
Thanks
+Pie Number of slices to send: Send
Hi Charley,
Line 4 is not giving the error as you are using the 'short circuit' && operator. This operator returns 'true' only if both arguments are true. Since the first argument 's != null' is false, it doesn't bother checking the second argument. As the argument is not evaluated, no NullPointerException is raised.
Hope that helps.
------------------
Jane
The cure for boredom is curiosity.
There is no cure for curiosity.
-- Dorothy Parker
[This message has been edited by Jane Griscti (edited December 03, 2000).]
See ya later boys, I think I'm in love. Oh wait, she's just a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 654 times.
Similar Threads
Mock Exam Question.Please anybody help me.
Eddie McNally's Jxam question...
Jxam
Why the code throws Exception?
Exception
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:43:08.