A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
Syntax:
if(condition)
statement;
else
if(condition)
statement;
else
if(condition)
statement;
else
statement;
The if Conditional statements is executed from top down approach. As soon one of the conditions of if is true, then the associated statement with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
/* Enter marks and print First div if marks>=60 Second div if marks >=45 and <60 otherwise print Third division */
import java.io.*;
class IfElseIfLadder
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int m;
System.out.print(“Enter marks : “);
h=k.readLine( );
m=Integer.parseInt(h);
if(m>=60)
{
System.out.println(“First division”);
}
else
{
if(m>=45)
{
System.out.println(“Second division”);
}
else
{
System.out.println(“Third division”);
}
}
}
}
The control will goto else section, if the value of variable m<60. In the else section, another set of if else statement is used to check whether m>=45 or not
import java.io.*;
class LogicalOperators
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int m;
System.out.print(“Enter marks :”);
h=k.readLine( );
m=Integer.parseInt(h);
if(m>=60)
{
System.out.println(“First division”);
}
if(m>=45 && m <60)
{
System.out.println(“Second division”);
}
if(m <45)
{
System.out.println(“Third division”);
}
}
}
Note: As we can see in above example, when we use logical operators, else section can be ignored.
/* Enter two values a and b and print the larger of the two */
import java.io.*;
class LargerNumber
{
public static void main(String args[] )
throws IOException
{
BufferedReader k=new BufferedReader(new InputStreamReader
(System.in));
String h;
int a,b;
System.out.print(“Enter two values :”);
h=k.readLine( );
a=Integer.parseInt(h);
h=k.readLine( );
b=Integer.parseInt(h);
if(a>=b)
{
System.out.println(“Larger is “+a);
}
else
{
System.out.println(“Larger is “+b);
}
}
}