Nested If-else statement

Nested if-else means inside body of if statement or else statment, another if-else block can be written. Example is given below



Example :


	// file: ifelstate1.java
// www.jgyan.com
class ifelstate1
{
public static void main(String arg[])
{
int a=10,b=20,c=13;
if(a<b)
{
if(c<b)
System.out.println("b is greater than a and c");
else
System.out.println("b is greater than a but smaller than c");
}
else
{
if(c>a)
System.out.println("a is greater than b and c");
else
System.out.println("a is greater than b but smaller than c");
}
if(a%2==0) // Body with curly braces.
{
System.out.println("a is even number");
}
else
{
System.out.println("a is odd number");
}
}
}
/*output
b is greater than a and c
*/


if-else-if ladder

java leverage programmer to simplify his code by using his own choice of multi selection control statement. In nested if-else, it's very tedious task to manage curly braces and code inside another block. If-else-if ladder can be used at the place of nested if-else



Syntax :

	if( condition_1 ) 
{
Statements;
}
else if( condition_2 )
{
Statements;
}
else if( condition_3 )
{
Statements;
}
else if( condition_4 )
{
Statements;
}
else if( condition_5 )
{
Statements;
}
else if( condition_6 )
{
Statements;
}
............
............
else if( condition_n )
{
Statements;
}
else
{

}


Example :


	//file: ifelstate2.java
//www.jgyan.com
class ifelstate2
{
public static void main(String arg[])
{
int grade=45;
if(grage >= 95)
{
System.out.println("Grade:A+");
}
else if(grage >= 90)
{
System.out.println("Grade:A");
}
else if(grage >= 80)
{
System.out.println("Grade:B+");
}
else if(grage >= 75)
{
System.out.println("Grade:B");
}
else if(grage >= 60)
{
System.out.println("Grade:C");
}
else if(grage >=45)
{
System.out.println("Grade:D");
}
else if(grage >=35)
{
System.out.println("Grade:E");
}
else
{
System.out.println("Grade:F");
}

}
}
/*output
Grade:D
*/