Iam confused with the code below.Could anyone help me. 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)) answer:A,C Thanks in advance.
Sunita Vontel
Ranch Hand
Joined: Aug 28, 2000
Posts: 72
posted
0
The answer is A and C coz & and | are not short circuit operators.so even if the fist condition is false it will try to check the second condition and hence the Exception. In the other cases when the compiler sees that first condition is false it wont test the second condition.
kishen uchil
Greenhorn
Joined: Aug 21, 2000
Posts: 14
posted
0
can anyone please tell me what the value in 's'variable is. i frankly dont understand the question itself.please help.
Well, s doesn't have to be a String. s is a reference to an object of a class that has a method length() defined. The key here is that if the reference is null then attempting to use the reference to call the method length() causes NullPointerException. B and D exhibit short circuit behavior and length() is not called if the reference is null. In A and C length() is called irrespective of the value of the first operand. Vani
kishen uchil
Greenhorn
Joined: Aug 21, 2000
Posts: 14
posted
0
thank you very much vani.explanation was really helpful.