Since 31 > 8, is should go into the first if statement, and since 31 < 100, it then should go into the else statement and output "hi". However the output of this program is "ther3". I do understand that System.out.print("ther3");
is outside both if statements and would be printed regardless. But why is System.out.print("hi");
not printed.
public static void main(String[] args) {
int x = 31;
int y = 8;
if (x > y) {
if (x > 100) {
System.out.print("Hello");
}
}
else
System.out.print("hi");
System.out.print("ther3");
}
CodePudding user response:
The reason that it didn't print "hi" is because the else
part belongs to the outer
if statement not inner
.
You can see the curly braces {}
of the outer if statement. It's closed before else. That's why it's not executed. You can change it and see the output once.
if (x > y) {
if (x > 100) {
System.out.print("Hello");
}
}
else
System.out.print("hi");
System.out.print("ther3");