else if statement in java with example

else if statement is used when multipath decision are involved.

Syntax:-

if(condition 1)
{
statement 1
}
else if (condition 2)
{
statement 2
}
else if (condition 3)
{
statement 3
}
.
.
.
else if (condition N)
{
statement N
}
statement

Note:-

# Condition can be expression or relation.
# If body of statement is only one statement than braces ({}) are not needed.
# Body of the statement may have one or more statement.
# Any one statement is executed not all.

Execution:-

The conditions are checked from top to bottom when true condition is found than statement related to that condition is executed and control is transfer to statement next to else is statement
when all condition are false than statement related to else is executed and control is transfer to statement next to else is statement

Examples:-

Program to solve following problem

Average marks Grade
100-75 1
74-50 2
49-30 3
29-30 4

import java.util.Scanner;

class group{
public static void main(String arg[]){
int mark;
Scanner data = new Scanner(System.in);
System.out.println("Enter the marks");
mark = data.nextInt();
if(mark <= 100 & mark >= 75)
System.out.println("1st class");
else if ((mark < 75)&(mark>=50))
System.out.println("2nd class");
else if ((mark < 50)&(mark>=30))
System.out.println("3rd class");
else
System.out.println("Last class");
}
}


Previous Code:-
Nesting of if-else statement

List Code:-
Java codes

Next Code:-
Increment operator

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top