File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operators 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 "operators" Watch "operators" New topic
Author

operators

harish shankarnarayan
Ranch Hand

Joined: Sep 12, 2005
Posts: 158
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...


Harish<br />SCJP 1.4 (85%)
Ram Munshi
Ranch Hand

Joined: Aug 09, 2005
Posts: 55
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


Ram Munshi
Cristina Vinuela
Greenhorn

Joined: Dec 12, 2005
Posts: 6
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

Joined: Nov 10, 2005
Posts: 7
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: operators
 
Similar Threads
SCJP Brainteaser (1)
object reference variables as literals?
What value does readLine() return when it has reached the end of a file
WA #1.....word association
Values of Hash Map to be 2-dimensional array