• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Operators

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Given the following definition:
String s = null;
Which code fragment will cause an exception of type NullPointerException to be thrown.
(A) if ((s != null) & (s.length()>0))
(B) if ((s != null) && (s.length()>0))
(C) if ((s != null) | (s.length()>0))
(D) if ((s != null) | | (s.length()>0))
Can anybody tell me what answers are true? And what are the reasons?
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only one that will NOT cause a NullPointerException is:
if ((s != null) && (s.length()>0))
&& is the "short circuited" logical AND - if the left result is false, it does NOT evaluate the right expression.
& and | evaluate both sides
| | is the short circuited logical OR, if the left result is true it does not evaluate the right expression. In this case the left result is false so it tries s.length().
The reason Java has both is because sometimes the side effect of evaluating the right expression is significant to program execution.
Bill

------------------
author of:
 
CLUCK LIKE A CHICKEN! Now look at this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic