When a if condition is included in the if block of some other if condition then those are called nested ifs.
We can have as many nested ifs and it can go into many levels.
class ClassifyPerson
{
public static void main(String arg[])
{
int age = 35;
char gender = 'F'; // M - Male, F - Female
if( age > 35 ) // outer if
{
if( gender == 'M' ) // LINE A
{
System.out.println("Man");
}
else
{
System.out.println("Woman");
}
}
else
{
if( gender == 'M' ) // LINE B
{
System.out.println("Boy");
}
else
{
System.out.println("Girl");
}
}
}
}
DESCRIPTIONHere we have two variables age
and gender
. In the outer if the condition age > 35
is checked, if its true
, the block starting with LINE A
is executed. The inner if
condition present in LINE A
checks for gender
and prints Man or Woman.
If age is less than 35 then the else
block starting with LINE B
is executed. The if
in LINE B
checks for gender
and prints Boy or Girl.
THINGS TO TRY
- Add one more variable
marks
of type int
to the above program and modify the program such that it prints Intelligent when marks
greater than or equal to 75, otherwise it prints Dull. and If age
greater than or equal to 35 and gender
equal to M it prints Man otherwise it prints Woman. Boy or Girl when age
less than 35.
Examples:
1. when marks
are 75, age is 35 and gender is F output should be Intelligent Woman
2. marks
are 40, age is 22 and gender is M output should be Dull Boy