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 Programmer Certification (SCJP/OCPJP) and the fly likes When does a NullPointerException occurs? 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "When does a NullPointerException occurs?" Watch "When does a NullPointerException occurs?" New topic
Author

When does a NullPointerException occurs?

Charley Wu
Greenhorn

Joined: Nov 30, 2000
Posts: 6
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
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
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).]


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
wood burning stoves
 
subject: When does a NullPointerException occurs?
 
Similar Threads
Eddie McNally's Jxam question...
Mock Exam Question.Please anybody help me.
Exception
Jxam
Why the code throws Exception?