aspose file tools*
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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When does a NullPointerException occurs?