Nesting of if – else statement in java with example

When a series of decision are involved, we may have to use more than one if else statement in nested form as shown below

Syntax

if(condition 1)
{
if(condition 2)
{
True - Block of Statement 1
}
else
{
false - Block of Statement 2
}
}
else
{
false - Block of Statement 3
}

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.
# Either true – block of statement or false – block of statement is executed, not both.

Execution:-

When both condition 1 and condition 2 are true than True - Block of Statement 1 is executed.
If condition 1 is true and condition 2 is false than false - Block of Statement 2 is executed.
If condition 1 is false than false – blocked statement 3 is executed.
In each case control is moved to statement that is next to if statement.

Examples:-

Program to solve following problem
The candidate is selected if his age and height is 18 and 5 and more respectively.

import java.util.Scanner;

class group{
public static void main(String arg[]){
int age, height;
Scanner data = new Scanner(System.in);
System.out.println("Enter candidate age");
age = data.nextInt();
System.out.println("Enter cadidate height");
height = data.nextInt();
if(age >= 18)
{
if(height >= 5)
System.out.println("The cadidate is selected");
else
System.out.println("sorry, candidate not selected");
}
else
System.out.println("sorry, candidate not selected");
}
}


Previous Code:-
if-else statement

List Code:-
Java codes

Next Code:-
else if statement

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top