google Ads

Monday, July 13, 2009

Nested if-else

Nested if-else statements

When a series of if –else statements are occurred in a program, we can write an entire if-else statement in another if-else statement called nesting. And the statement is called nested if.

Syntax:

if(condition 1)
{
statements 1;
}
else if(condition 2)
{
statements 2;
}

else if(condition 3)
{
statements 3;
}
else
{
statements 4;
}

statements 5;

If Condition 1 is true Statements 1 and Statements 5 will be executed. If condition 1 is false Condition 2 (Statements 2) and Statements 5 will be executed. If Condition 1 and Condition 2 is false, then Condition 3 (Statement 3) and Statements 5 will be executed. If Condition 1, Condition 2 and Condition 3 is false, then process goes to else part and Statements 4 and Statements 5 will be executed.

Note: Statements 5 will be executed

Note that the third if-else statements is nested in the second else statement and second if-else statements is nested in the first else statements. If the condition in the first “if” statement is false, then the condition in the second if statement will be executed, if the second “if” statement is false, then the condition in the third “if” statement will be executed. If it is false then the final else statement is executed.


Example:

if (a>10)
{
System.out.println(“A Value is greater than 10”);
}
else if(a<10)
{
System.out.println(“A value is less than 10”);

}
else if(a==10)
{
System.out.println(“A value is :” + a);
}
System.out.println(“A= “ +a);


Similarly, we can construct any number of if-else statements in nested fashion, that is called if-else ladder.
If you want to test more than one condition in if statement the logical operator are used as specified below. These are used to combine the results of two or more conditions.
Operator Meaning
&& Logical And
Logical Or
! Logical Not



Example: 1

import java.io.*;
Public class biggest
{
Public static void main(String args[])
{
int a,b,c;
a=15; b=42; c=24;
}
if(a>b)&&(a>c)
{
System.out.println(“A is biggest number”);
}
else if(b>c)
{
System.out.println(“B is biggest Number”);
}
else
{
System.out.println(“C is Biggest Number");
}
System.out.println(“A = “ +a +”B = “+ b + "C= " + c);
}

Output will be

B is Biggest Number

A= 15 B= 42 C= 24


No comments:

Post a Comment