This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operators

 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}

A single ampersand here would lead to a NullPointerException

how???
wat actually happens...
 
Ram Munshi
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While using short circuit opeartor( &&,||) ,if the LHS is true in case of || or if LHS is false in case of && the RHS is not evaluated.
while using & and | both sides are evaluated ,so while invoking any method on null ref. would result in null pointer exception.
I hope it answers your question.

Ram
 
Cristina Vinuela
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The single & evaluates both operands regardless of the result of the first one. So, if a == null when it evaluates a.length() a NullPointerException is thrown.

The && only evaluates the second operand if the first one is true, because if it is false the whole expression is false, so it doesn't go on, that is why it is called a shortcircuit operator.

Hope that helps

Cris
 
rey anz
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The '&' operator evaluates both expressions while '&&' is a short circuit evaluator. Here first expression on evaluation gives 'false' and the second would throw an exception. When '&&' is used the first expression makes the result 'false' even without evaluation of the second expression("short-circuited"), but with '&' both sides are evaluated, hence an exception will be thrown.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic