| Previous | Home | Next |
It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
syntax :
if(condition)
{
if(condition)
{
true statement;
}
else
{
false statement;
}
}
else
{
if(condition)
{
true statement;
}
else
{
false statement;
}
}
Example :
class Max3
{
public static void main(String args[])
{
int a,b,c,max;
a=3;
b=8;
c=4;
if(a>b)
{
if(a>c)
{
max=a;
}
else
{
max=c;
}
}
else
{
if(b>c)
{
max=b;
}
else
{
max=c;
}
}
System.out.print("Max is "+max);
}
}
output :
Max is 8
An if statement can be followed by an optional else if...else statement,
syntax :
if(condition 1)
{
//Executes when the condition 1 is true
}
else if(condition 2)
{
//Executes when the condition 2 is true
}
else if(condition 3)
{
//Executes when the condition 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example :
class Day
{
public static void main(String args[])
{
int n;
n=5;
if(n==1)
{
System.out.print("sunday");
}
else if(n==2)
{
System.out.print("Monday");
}
else if(n==3)
{
System.out.print("tuesday");
}
else if(n==4)
{
System.out.print("Wednesday");
}
else
{
System.out.print("Invalid !");
}
}
}
output :
Invalid !
| Previous | Home | Next |