Nested if in java

By: aathishankaran Viewed: 153135 times  Printer Friendly Format    


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 typed of TV is colored [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 “EnternTV type (Color /BW):”;
	accept Type;
	display “Enter TV screen size:”;
	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.


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial