Topics Index

ShortCircuit Operator

If you need explanation Read this topic

If you need Answer Take test on this topic

ShortCircuit Operator
What will be the output of the following program?
public class checking
    public static void main(String s[])
        int c = 0, d = 50, e = 50;
        boolean b = (c == 1) && (++e < 100);
        System.out.println("e = " + e);
        boolean f = (++e < 100) && (c == 1);
        System.out.println("e = " + e);

A. e = 50
e = 50
B. e = 50
e = 51
C. e = 51
e = 51
D. e = 51
e = 52
E. Compilation Error or Runtime Error
Topic: Short Circuit Logical Operators In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Answer is B.....
boolean b = (c==1) && (++e<100);
  in the above step,first c==1 is evaluated and that is false (because false && (anything) is false) and so the (++e,100) will not be executed.. (Expressions inside the () are evaluated first  with associativity left to right)
  So value of e after this step is 50;

boolean b =(++e  < 100) && (c==1);
in the above step,first(++e <100) is evaluated (e is incremented to 51) and since it is true,next expression is also evaluated;
So value of e after this step is 51;

Posted by Shashanka Mogaliraju    2014-12-08 12:13:42

ans b....Java provides two interesting Boolean operators not found in many other computer languages.

These are secondary versions of the Boolean AND and OR operators, and are known as
short-circuit logical operators.

Java will not bother to evaluate the right-hand operand
when the outcome of the expression can be determined by the left operand alone.

This is
very useful when the right-hand operand depends on the value of the left one in order
to function properly.

coming to this program initialy c asssigned with 0 e with 50. boolean b assigned with (c==1)&&(++e<100) it acts lik if condition. here c==1 fails and here AND used ,if both the func true thn only b c==1 faild,so no need to check rightside conditions of &&.so preincrement of e not get executed.
e value not changed e=50 same value remains. sop prints e=50.

f is assigned with (++e<100)&&(c==1) here leftside of && condition true 50<100 and postincrement happens .thn we need to check right side.bcz both condition return true thn only f true. 2nd condition faild so f false. sop prints e=51

Posted by Maheshwari Natarajan    2014-12-08 17:46:37

This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Sai Ram,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Sai Ram. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2014-12-09 03:15:07

© meritcampus 2019

All Rights Reserved.

Open In App