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
2 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
The statement that brings the control back to the calling method is:
- break
- System.exit(0)
- continue
- return
Differentiate between if else if and switch-case statements
An air-conditioned bus charges fare from the passengers based on the distance travelled as per the tariff given below:
Distance Travelled Fare Up to 10 km Fixed charge ₹80 11 km to 20 km ₹6/km 21 km to 30 km ₹5/km 31 km and above ₹4/km Design a program to input distance travelled by the passenger. Calculate and display the fare to be paid.
Write a program to input three numbers (positive or negative). If they are unequal then display the greatest number otherwise, display they are equal. The program also displays whether the numbers entered by the user are 'All positive', 'All negative' or 'Mixed numbers'.
Sample Input: 56, -15, 12
Sample Output:
The greatest number is 56
Entered numbers are mixed numbers.