Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointerException

 
mita
Ranch Hand
Posts: 50
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Which code fragments cause an object 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))
Could someone please explain me why the answers here are A & C whereas in the following
Which code fragments cause an object 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)) the answer is A, B, C, D.
Please explain me how it works in these codes.
Thanks in advance
Mita

 
Ajith Kallambella
Sheriff
Posts: 5782
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mita,
This question deals with the difference between short-circuit logical operators and bitwise operators in the way they evaluate expressions.
For an && expression, if the first operand evaluates to false, the second operand is never evaluated.
Similarly for an | | expression, if the first operand evaluates to true, the second operand is never evaluated.
Unlike the logical short-circuit operators, the bitwise operators & and | always evaluate both the operands and hence can cause NullPointerException.

Hope this helps,
Ajith
 
mita
Ranch Hand
Posts: 50
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Ajith.That sure helped a lot.
Mita
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic