0
Can't understand the answer of this question from Challenge
This code was in a challenge: Write the output of: int a=8; int b=9; if((++a>8) && (--b>=9)) System.out.println(b); else System.out.println(a) Here the correct answer was given 9. But I don't understand; since the logic inside if is false(--b is 8 so not >= 9) so the code should execute else statement and print a right? And a is 8. However the correct answer is 9 ! So does incrementing inside if statements affect variables value? Can you tell me where I'm mistaken?
4 Answers
+ 5
Yes you are right
The statement goes to else to print a, which after the ++a inside if, becomes 9
+ 18
1 more point, if 1st condition is false, then next condition will not be checked [it could have affected value of b here if ++a>8 was false]
//try it đ [many java challenges are on this short-circuiting concept also]
+ 3
if((++a>8)&&(--b>=9)){//}
++a is short hand notation for a = a+1
--b is short hand notation for b= b-1
Here new value of a will be 9
new value of b will be 8
The above statement will be like
if((9>8)&&(8>=9)) i.e. if((true)&&(false))
Since if condition evaluates to false, so else block will be executed
Inside else block the statement in printing value of a
+ 3
Yes, a++ affect the a var. Its like:
a= a + 1;