Java Reference
In-Depth Information
The if-else statement can be nested, as shown:
if (num1 > 50) {
if (num2 < 30) {
num3 = num3 + 130;
}
else {
num3 = num3 - 130;
}
}
else {
num3 = num3 = 200;
}
Sometimes it is confusing to determine which else goes with which if in nested if-else statements. Consider
the following piece of code:
int i = 10;
int j = 15;
if (i > 15)
if (j == 15)
System.out.println("Thanks");
else
System.out.println("Sorry");
What will be the output when this snippet of code is executed? Will it print “Thanks” or “Sorry” or nothing? If you
guessed that it would not print anything, you already understand if-else association.
You can apply a simple rule to figure out which else goes with which if in an if-else statement. Start with the
"else" and move up. If you do not find any other "else," the first "if" you find goes with the "else" you started
with. If you find one "else" in moving up before you find any "if," the second "if" goes with the "else" you started
with, and so on. In the above piece of code, starting with "else" the first "if" you find is "if (j == 15)" and so the
"else" goes with this "if." The above piece of code can be rewritten as follows:
int i = 10;
int j = 15;
if (i > 15) {
if (j == 15) {
System.out.println("Thanks");
}
else {
System.out.println("Sorry");
}
}
Because i is equal to 10, the expression i > 15 will return false and hence the control would not enter the if
statement at all. Therefore, there would not be any output.
Note that the condition expression in an if statement must be of the boolean type. Therefore, if you want to
compare two int variables, i and j , for equality, your if statement must look like the following:
if (i == j)
statement
 
Search WWH ::




Custom Search