The if constructed in java can be nested. In other words, an if construct can be present inside the body of another if construct.
Example:
To decide discount percentage for selling a TV, the following are to be changed:
Type of TV:
If Black and White [B], discount will be 5% of selling price.
If type of TV is color [C], verify the size of TV screen:
For 14 inches, discount is 8% of selling price
For 21 inches, discount is 10% of selling price
class PROGRAM_BUY_TV {
char Type;
integer Size;
integer Dis_Perc=0;
display "Enter TV type (C for Color and B for BW):";
accept Type;
display "Enter TV screen size 14 or 21:";
accept Size;
if(Type == 'B')
{
Dis_perc=5;
}
else
{
if(Type == 'C')
{
if(Size==14)
{
Dis_Perc=8;
}
else
{
Dis_Perc=10;
}
}
}
}
It is very important to be sure which else construct goes with which if construct. In the examples, we have indented the else-related statements with their corresponding if-related statements. This indentation greatly aids the clarity of the code for a reader. Also, the number of opening if ¦ else braces must match with the number of closed if ¦ else braces.