IntelliJ Java IDE
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Exception" Watch "Exception" New topic
Author

Exception

Santoo
Greenhorn

Joined: Aug 04, 2000
Posts: 6
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
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
can anyone please tell me what the value in 's'variable is.
i frankly dont understand the question itself.please help.
Sunita Vontel
Ranch Hand

Joined: Aug 28, 2000
Posts: 72
Its a string
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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
thank you very much vani.explanation was really helpful.
 
jQuery in Action, 2nd edition
 
subject: Exception
 
Threads others viewed
NullPointerException
Operators
Difference between l (logical OR) and II (Shortcircuited OR)
Mock Exam Question.Please anybody help me.
Jxam Question
IntelliJ Java IDE