Originally posted by Paul Salerno:
Which of the following may throw an exception?
1 if ((s !=null) | ( i =s.length()))
2 if ((s ==null) | ( i =s.length()))
3 if ((s !=null) ||( i =s.length()))
4 if ((s ==null) || ( i =s.length()))
Select all best answers?
A. 1
B. 2
C. 3
D. 4
Their answer: A,B,D
I really dont understand what this question is? Can someone throw some light?
I think the answer given is wrong.The answer should be A,B,C.
First in the RHS part of the IF condition, it should be an equality operator and not an assignment operator.If it is assingment operator then it will give the following error.
"operator | or || cannot be applied to boolean,int"
Let us take the following code using case 4:
public class abc
{
public static void main(String args[])
{
String s= null;
int i=0;
if ((s == null) || ( i == s.length()));
}
}
It will not give any exception becos of short circuit operator.
Since case 1 and 2 are not using || operator, it will throw exception when s is null.
In case 3, if s is null, it will then check the s.length(). so it will give an exception.
So A,B and C are the answers.
Am i right?