0

Order of execution in nested if-else loop

Why does the "else" statement works as if it is just another "if". Let me explain. What I expected from the following code is NOT to work. Since I removed {}, the last "else" statement shouldn't be triggered, because we already have "else" condition(to print: "Boy") P.S. A follow-up question- why use nested loops anyway? I know it looks better, but in the current case I could've just created three "if" statements and be good with it int x = 3; if (x >=10 ) //{ if (x >= 21 ) System.out.println("Man"); else System.out.println("Boy"); //} else System.out.println("Cub");

21st Dec 2017, 8:13 AM
Yanis
Yanis - avatar
2 ответов
+ 8
The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong.and if block is evaluate first if it is true it goes in the body of loop and if the condition is false it exit from if block and execute next statement then it execute else part int x = 3; if (x >=10 ) //{ if (x >= 21 ) System.out.println("Man"); else System.out.println("Boy"); //} else System.out.println("Cub"); in this case first if statement check where condition is false so it quit if body and direct go to the body of else statement and execute it and print Cub
21st Dec 2017, 8:34 AM
GAWEN STEASY
GAWEN STEASY - avatar