This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.

here is the q,answers and some explanations: Given the following definition: String s = null; Which code fragment will cause an exception of type NullPointerException to be thrown. ##ans1## if ((s != null) & (s.length()>0)) ##ans2## if ((s != null) && (s.length()>0)) ##ans3## if ((s != null) | (s.length()>0)) ##ans4## if ((s != null) | | (s.length()>0)) ##ans5## None of the above. ##correct## 1,2,3,4 i checked only 1,3,4 and even I compiled and saw that 2 is not a correct answer,i have doubt about the explanation-for answer 2 "Answer 1 must be fully evaluated. The LHS is true and so the RHS needs to be evaluated to ensure the entire expression is true. This is an AND operation, and if the LHS is true, then the RHS must be evaluated for the expression to be true. Answer 2 is the same as above. Both sides need to be evaluated for an AND expression to be true (if the LHS is true, that is).." am i missing something? rgds, cristi

Hi Cristi, You are missing the fact that '&&' is shortcircuit operator. In short circuit operator evaluation, if the final result can be decided by knowing the result of the first operand then the other operand is NOT evaluated at all. So the answer 2 is correct. Hope this clears your doubt.

------------------ Regards --------- vadiraj

***************** There's a lot of I in J. *****************

Regards<BR>---------<BR>vadiraj<P><BR>*****************<BR>There's a lot of I in J.<BR>*****************

In case of 2nd option----the first boolean expression will be 'false' so the second part of the AND Logical operator option will not be calculated.So,There should be no Exception thrown in the 2nd option.

Cristi Tudose
Ranch Hand

Joined: Dec 25, 2000
Posts: 53

posted

0

sorry vadiraj,u are right about theory but here first part s!=null is avaluate to false and false && X always evaluate false(without evaluate X) so i think the correct answer should be 1,3,4 as golu jain observe too. your opinion remain the same? rgds, cristi

Originally posted by vadiraj vd: Hi Cristi, You are missing the fact that '&&' is shortcircuit operator. In short circuit operator evaluation, if the final result can be decided by knowing the result of the first operand then the other operand is NOT evaluated at all. So the answer 2 is correct. Hope this clears your doubt.