Computer Applications
Choose the correct equivalent of the given if-else statement:
if(x % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
Java Conditional Stmts
3 Likes
Answer
System.out.println(x % 2 == 0 ? "Even" : "Odd");
Reason — The ternary operator must be placed inside System.out.println() for proper execution. The ternary operator condition ? value_if_true : value_if_false is used as a shorthand for if-else.
Here, x % 2 == 0 checks if x is even. If true, "Even" is printed; otherwise, "Odd" is printed. Hence, this single-line statement is equivalent to the given if-else block.
Answered By
1 Like
Related Questions
A student executes the following program segment and gets an error. Identify the statement which has an error, correct the same to get the output as WIN.
boolean x = true; switch(x) { case 1: System.out.println("WIN"); break; case 2: System.out.println("LOOSE"); }A triangle is said to be an 'Equable Triangle', if the area of the triangle is equal to its perimeter. Write a program to enter three sides of a triangle. Check and print whether the triangle is equable or not.
For example, a right angled triangle with sides 5, 12 and 13 has its area and perimeter both equal to 30.Which of the following is not true with regards to a switch statement?
- checks for an equality between the input and the case labels
- supports floating point constants
- break is used to exit from the switch block
- case labels are unique