+ 2

What the following statement means and what will b the output??

int x=5; x= ! (x>8)?1:0; System.out.println (x);

27th Jul 2017, 6:57 PM
Aman Kumar
3 odpowiedzi
+ 2
1 ! means negation, i.e, !(true) == false. Ternary operator is used for writing a simple if-else statement on a single line. It's syntax is: condition ? value_if_true : value_if_false; You can write it in a traditional if-else block as: if (condition) { // code if condition was true } else { // handle false case } As x = 5, x > 8 evaluates to false and !(false) == true. So, x = true ? 1 : 0; evaluates to x = 1.
27th Jul 2017, 7:13 PM
its_mastan
its_mastan - avatar
+ 2
Meaning: 1) int x=5; It creates an int variable called x. Its value is 5 2) x=! (x>8)?1:0; It checks if x value is not greater than 8 (x value is 5), so the returned value is 1 (because of result is true: x is not greater than 8) and then assigns 1 to x 3) System.out.println (x); It prints x Output: 1 Remember: (condition)?statementIfTrue:statementIfFalse; is equivalent to: if (condition){ statementIfTrue; } else { statementIfFalse; }
27th Jul 2017, 7:13 PM
Tiago Soares
Tiago Soares - avatar
0
as x=5 therefore (x>8)==false hence !(x>8)==true here the result will be 1 hope this was helpful 🙂
27th Jul 2017, 7:49 PM
Vinayak Agrawal
Vinayak Agrawal - avatar