Forums Register Login

javaprepare question

+Pie Number of slices to send: Send
public class ShortCkt {
public static void main(String args[]) {
int i = 0;
boolean t = true;
boolean f = false, b;
b = (t || ((i++) == 0));
b = (f || ((i+=2) > 0));
System.out.println(i);
}
}
The answer acc.to javaprepare is 2.
I think it's 3.
Pl.help.
+Pie Number of slices to send: Send
Have you tried it? I'll bet that will tell you the correct answer.
Corey
+Pie Number of slices to send: Send
The conditional or || doesn't evalute the right operand "(i++) == 0)" if the left one "t" is true. Thus 2 is printed.
Similarly, && doesn't evalute the right operand if the left is false.
This is done for the sake of speed.
+Pie Number of slices to send: Send
Yes,i tried it out.The o/p is 2.
After the statement: b=t||((i++)==0));
The value of i is 0,not 1.
Why is it so?That's my confusion.
+Pie Number of slices to send: Send
Thanks Jose,for the clarification.
Got it.
+Pie Number of slices to send: Send
 

Originally posted by geetha nagarajan:
After the statement: b=t||((i++)==0));
The value of i is 0,not 1.
Why is it so?That's my confusion.


That would have been a great question to start with.
+Pie Number of slices to send: Send
The operation within the if () clause does not proceed testing an operation if it first meets a condition that equates to a true statement.
If reading 'if (true, ((i++) == 0))' the condition starts checking the left side of the operation which validates to true. Because the boolean is true, it continues performing the operation within the if block and doesn't check the right side of the condition. The '||' operation only looks for a true result first, and if successful (true), performs no other operations (meaning, the right hand side does not get looked at).
In the case of 'if (false, ((i+=2) > 0))' the condition that is first checked is false, which in the case of an '||' or operation, it looks to find a condition that is equal to true, and in this case, the operation i+=2 > 0 is performed.
This only works because the '||' condition on the left first produced a false result. The condition on the right executes because the '||' condition found no true statement.
In your response, if the condition of the boolean in the first check was false, you would get the value of '3'.
Execute the code and play around to see how it works.
Cheers,
Lloyd Wilson
Are you okay? You look a little big. Maybe this tiny ad will help:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 625 times.
Similar Threads
Operator question
question from anilbachi site
what's the output
short ckt ques from mock exam
question from javacross.com
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:48:07.