Java program for nested if statement
Introduction
We use nested if-else statements when multiple decisions are involved in the java program. We can nest many if statements or if-else statements in the program based on the decisions. We can use one if or if-else statement inside another if/if-else statement
Syntax
The sample syntax of nested if statement in the simplest form is :
If (Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
If (Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
Java Program
We will write a simple java program to show the syntax usage of the nested if in a Java program.
import java.util.Scanner;
/***********************************************************
* NestedIfStatement.java
* @program : Java program using nested if loop
* @web : www.testingdocs.com
* @version : 1.0
* ************************************************************/
public class NestedIfStatement {
public static void main(String[] args) {
Scanner console= new Scanner(System.in);
System.out.print("Enter Student score in a subject:= ");
int score = console.nextInt();
if(score >= 40) {
System.out.println("Student got Pass mark.");
if(score >= 70) {
System.out.println("Student got distinction score.");
}
}
}
}
In this program, two variables a & b are initialized to some arbitrary values. Using nested if statement the output of the variables is printed.
Program Output
Enter Student score in a subject:= 75
Student got Pass mark.
Student got distinction score.
Screenshot
