- The statement inside of an
if
or else
option can be another if-else
statement. Placing an if-else
inside another is known as nested if-else
constructions. For example:
if (expression1)
{
if (expression2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement3;
}
-
Here, your braces will need to be correct to ensure that the ifs and elses get paired with their partners.
-
The above example has three possible different outcomes as shown in the following chart:
- Technically, braces are not needed for if and if-else structures if you only want one statement to execute. However, caution must be shown when using else statements inside of nested if-else structures. For example:
if (expression1)
if (expression2)
statement1;
else
statement2;
Indentation is ignored by the compiler, hence it will pair the else statement with the inner if. If you want the else to get paired with the outer if as the indentation indicates, you need to add braces:
if (expression1)
{
if (expression2)
statement1;
}
else
statement2;
The braces allow the else statement to be paired with the outer if
.
Important Concept |
However, if you always use braces when writing if and if-else statements, you will never have this problem. |
|
-
Another alternative to the example in Section 4 makes use of the && operator. A pair of nested if statements can be coded as a single compound && statement. Both of these blocks of code would have the exact same effect, but the second one is slightly easier to read.
if(expression1)
{
if(expression2)
{
statement1;
}
}
//or...
if (expression1 && expression2)
{
statement1;
}
The second block of code makes the conditions clearer to another programmer.
- Consider the following example of determining the type of triangle given the three sides A, B, and C.
if ( (A == B) && (B == C) )
{
System.out.println("Equilateral triangle");
}
else if ( (A == B) || (B == C) || (A == C) )
{
System.out.println("Isosceles triangle");
}
else
{
System.out.println("Scalene triangle");
}
If an equilateral triangle is encountered, the rest of the code is ignored. This can help to reduce the execution time of a program.