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.
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.
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
Post by:autobot
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