0

Conditional Operator

int i,k; i=10; k=i<0? -i:i; System.out.println(k); //outputs 10 i=-10; k=i<0? -i:i; System.out.println(k); // Also Outputs 10, WHY? shouldn't it print -10?

12th Jan 2017, 7:35 PM
Divyanshu Bhatnagar
Divyanshu Bhatnagar - avatar
3 ответов
+ 2
- -10 = +10....it's math -10 is smaller than 0 so it returns - -10
13th Jan 2017, 12:18 PM
FreakManMega
+ 1
It's because of the ternary conditional statement, combined with an assignement: the assignement is done last, after the right part of the equal sign was evaluated... The ternary conditional shortcut work as this: test ? expression_if_true : expression_if_false ; So, in the condition of your code ( i<0 ), you can now see that if i<0 ( i is negative ) -i ( so, now positive value of i ) is assigned to variable cas 'k', else, i is positive, not negative and its unchanged value is assigned to 'k': this line assign to 'k' the absolute value of 'i'...
12th Jan 2017, 7:54 PM
visph
visph - avatar
0
Yes of course. I didn't pay attention to it. Thanks.
13th Jan 2017, 12:48 PM
Divyanshu Bhatnagar
Divyanshu Bhatnagar - avatar