0

Can someone pls explain the output of this snippet

int x=0; for (int z=0; z<5; z++) { if((z>3) && (++x>2)) { x+=7 } } System.out.print(x);

11th Jul 2018, 10:39 AM
Ashay Singh
Ashay Singh - avatar
4 odpowiedzi
+ 5
when your if statment is checked z = 4 , it then increments x by 1 as it checks conditions as its still false no further increments are made and the loop ends. z<=6 will allow the if statement to return true and incremenet x by 7
11th Jul 2018, 1:25 PM
D_Stark
D_Stark - avatar
+ 2
int a = 0; boolean q = false && ++a>-5; System.out.println(a); this prints 0 and if you put '||' it prints 1 I think statement after false && doesn't get executed so x doesn't increase while z<3 then x becomes 1 then loop finishes but I am not sure
11th Jul 2018, 12:34 PM
Mert Yazıcı
Mert Yazıcı - avatar
0
Somebody else had this question and we were all very confused. The output appears to be 11, but somehow it isn't. Is it a challenge question?
11th Jul 2018, 11:28 AM
James
James - avatar
0
Here && operator works as follows : a&&b If a is false then the compiler does not evaluate the value of b as we know that the output is going to be false. So over here x is never incremented except when z=4 but the value of x at z=4 is 1 but in the x must be greater than 2 to enter the if block . Therefore According to me it should be 1 as it was incremented once in the block
4th Sep 2019, 2:25 PM
Ashutosh Srivastava
Ashutosh Srivastava - avatar