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 2 of 3.

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

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

Avni said:   7 years ago
Why y =0 in first case, why not 1?

Udaya said:   8 years ago
Good explanation, Thanks @G. Vivek.

Sai kiran said:   8 years ago
Awesome explanation @Vivek.

Gajendra chouriya said:   8 years ago
Thanks for the explanation @G.vivek.

Magesh said:   2 decades ago
Can any one please mention what is short circuit operator?

Sunny deol said:   9 years ago
Now I understand this, thank you @Nataliia.

Aashish said:   9 years ago
Thanks for your explanation @Arnold Villasanta.

Nataliia said:   9 years ago
class Main {
public static void main(String[] args) {
int x = 0;
int y = 0;
for (int z = 0; z < 5; z++) {
System.out.println("Before if: " + x + " " + y);
if ((++x > 2) && (++y > 2)) {
System.out.println("Before inc: " + x + " " + y);
x++;
System.out.println("After inc: " + x + " " + y);
}
System.out.println("After if: " + x + " " + y);
}
System.out.println("Result : " + x + " " + y);
}
}

Console:

Before if: 0 0
After if: 1 0
Before if: 1 0
After if: 2 0
Before if: 2 0
After if: 3 1
Before if: 3 1
After if: 4 2
Before if: 4 2
Before inc: 5 3
After inc: 6 3
After if: 6 3
Result : 6 3


Post your comments here:

Your comments will be displayed after verification.