Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 7)
7.
What will be the output of the program?
class Test 
{
    public static void main(String [] args) 
    {
        int x= 0;
        int y= 0;
        for (int z = 0; z < 5; z++) 
        {
            if (( ++x > 2 ) && (++y > 2)) 
            {
                x++;
            }
        }
        System.out.println(x + " " + y);
    }
}
5 2
5 3
6 3
6 4
Answer: Option
Explanation:

In the first two iterations x is incremented once and y is not because of the short circuit && operator. In the third and forth iterations x and y are each incremented, and in the fifth iteration x is doubly incremented and y is incremented.

Discussion:
31 comments Page 4 of 4.

Divya said:   1 decade ago
There are 2 types of short circuit operators.

1. Short circuit AND (&&)
2. Short circuit OR (||)

Now in the and case if first condition is false then the second is never evaluated as true and false gives you false only. In short circuit OR if first condition is true the second one is never evaluated as true OR false gives you true only. So its basically a short cut.


Post your comments here:

Your comments will be displayed after verification.