Quizzes Assignments Puzzles Easy exercises Required knowledge |
< |
Java Puzzles Green = Easy, Blue = Normal, Red = Hard Select 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 By title |
> |
---|
The combination of operators and conditional statements appear in almost every program. Every Java programmer should master all types
of conditional statements. Therefore, I focus to offer that in different ways in my puzzles and quizzes. Please, always check out the explanation of the answer if you have doubts.
Java puzzle 11: Operators and conditional statements
Level: Easy
What is the output of this program and why?
public class Operator { public static void main(String[] args) { int i = 2; int i2 = 4; int i3 = 7; if(i + i2 > i3 || i2 > i3 || i + i3 >= 9) { if(i2 == i + 2 && i2 < i) { System.out.print("x"); } System.out.print("z"); } else { System.out.print("y"); } } }
Author: Sar Maroof
Answer explanation
- The first if statement if(i + i2 > i3 || i2 > i3 || i + i3 >= 9) uses the conditional operator || (OR). By using || operator, the condition is true if one of the operands returns true.
i + i2 > i3 returns false. i2 > i3 returns false. i + i3 >= 9 returns true. Therefore the if block is executed and the else block is ignored. - By using the conditional operator && (AND) see the second statement if(i2 == i + 2 && i2 < i) both operands must return true otherwise the block wouldn’t be executed. i2 == i + 2 returns true.
i2 < i returns false. Therefore the block is not executed and the letter x is not written to the standard output. - The statement System.out.print(“z”); is inside the first conditional statement, which returns true. Therefore, the letter z is written to the standard output.
Suggested Articles
![]() ![]() ![]() |