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:
30 comments Page 3 of 3.

Aayushi jain said:   7 years ago
Why y is not get executed?

Preethi said:   7 years ago
Thank you good explanation @G.Vivekananda.

Aparna said:   7 years ago
Hi, Please explain this problem using OR.

Swapnil said:   7 years ago
Thank you so much @Arnold.

Niharika patidar said:   6 years ago
Please explain to me.

What is the reason that ++y is not executed for the first two times?
(1)

Anu said:   6 years ago
Thanks @Saranya and @G. Vivek.

Unknown said:   6 years ago
output of int z=2; while(z<20) if((z++)%2==0) system.out.println(z);

Moha said:   5 years ago
x=1 >2 wrong
z++
z=1
x=2>2 wrong
z++
z=2
x=3>2 yes
&&
1>2? wrong
z=3
x=4
2>2 rong
z=4
x=5
3>2 yes.

x++ x=6.
So, o/p: 6 3.
(5)

Sushaja said:   3 years ago
@Arnold.

Thank you for explaining the short circuit operator's operation in detail.

Keerthi said:   2 years ago
@All.

Check the first condition and till it is true it won't go to the second condition so when x becomes 3 and the condition satisfies (3>2) then only condition two comes into consideration like y=1 then x also increments by 4.
(2)


Post your comments here:

Your comments will be displayed after verification.