else if ladder
Else if ladder is a multi-path
decision making statement.It contains many number of conditions but when the compiler founds a certain condition which is to be true then it executes that statement only.
We can say it as a multi-path decision chain of if’s.
Syntax
if( condition1 )
{
// condition1 if block
}
else if( condition2 )
{
// condition2 if block
}
else if( condition n)
{
//condition n if block
}
else
{
// else block
}
How else-if ladder works? -
- Compiler first starts to evaluate the conditions from the first statement of the if and then goes executing one by one downwards.
- As soon as the true condition is found, the statement associated with it is executed and the control is transferred to the statement of that block.
- When all conditions of the else-if ladder becomes false, then the final else means default block statement is executed.
Example - Calculating grades of student based on Obtained Marks.
In this example we are displaying the grades of student by accepting throw commandline argument
Assume we are passing 90
class elseIfLadder
{
public static void main(String args[])
{
int marks = Integer.parseInt(args[0]);
char grade;
if (marks < 35)
grade = 'F';
else if (marks >= 35 && marks <= 49)
grade = 'C';
else if (marks >= 50 && marks <= 60)
grade = 'B';
else if (marks >= 61 && marks <= 100)
grade = 'A';
else
grade = 'F';
System.out.println("You got : "+grade);
}
}
Note : If there is only one statement in the block then it can be written without curly brackets. |
Output
You got : 90