If else in Java | Nested if-else, Example

An if else in Java is a two-way conditional statement that decides the execution path based on whether the condition is true or false.

In other words, if-else statement is used to perform a specific action (task) depending on whether a specified condition is true or false.

Here, an action signifies a statement or a group of statements.

A one-way if statement executes a statement if and only if the specified condition is true. If the condition is false, nothing will be done.

But suppose we want to take alternative actions when the specified condition is false. In this case, we will use a two-way if-else statement.

A two-way if-else statement in Java is used to route program execution through two different paths based on whether the condition is true or false.

The syntax for two way if-else statement is as follows:

if (boolean-expression or condition) {
    statement1; //  For true case.
}
else {
   statement2; // For false case.
}

Here, each statement represents a single statement or a block of statements enclosed in curly braces ( { }). The condition is any boolean expression that returns a boolean value.

The else clause is an optional part. It means that else clause part can be omitted if not required. This convention can be followed in all control statements in Java.

The flowchart for two way if-else statement is shown in the below figure.

Java If-else flowchrat diagram

Let’s understand how two-way if-else statements work in Java.

If the condition specified after is true, then statement1 is executed. If the condition is false, statement2 (if it exists) is executed. In no case will both statements be executed at a time.

For example, consider the following code:

int passMarks = 40;
if(passMarks >= 40) {
   System.out.println("Pass")
}
else {
   System.out.println("Fail")
}

If the boolean expression evaluates to true i.e. if passMarks >= 40 is true, it will display a message “Pass” on the console. If it is false, the message “Fail” will display.

As usual, the braces can be omitted if there is only one statement within them.

Let’s take another example of using the if-else statement. This example will verify whether a number is even or odd. The code is as follows:

if (number % 2 == 0)
  System.out.println(number + " is even.");
else
  System.out.println(number + " is odd.");

 Example Program based on Java If else statements


Let’s take some example programs based on if-else statements in Java.


1. Let’s create a program where we will take marks as input of five subjects and calculate the total marks, percentage, and grade. Look at the program source code.

Program source code 1:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class to take input.
   Scanner sc = new Scanner(System.in);
   
System.out.println("Enter the marks of Physics ");
 int phyMarks = sc.nextInt();
System.out.println("Enter the marks of Chemistry ");
 int chemMarks = sc.nextInt();
System.out.println("Enter the marks of Maths ");
 int mathsMarks = sc.nextInt();
 
System.out.println("Enter the marks of English ");
 int engMarks = sc.nextInt();
System.out.println("Enter the marks of Computer ");
 int compMarks = sc.nextInt();
 
float totalMarks = phyMarks + chemMarks + mathsMarks + engMarks + compMarks;
System.out.println("Total marks in five subjects: " +totalMarks);
float myPer = totalMarks /5;
System.out.println("My percentage: " +myPer);

if(myPer >= 80){ // Checking percentage to find grade using if else statement.
 System.out.println("Grade A");	
}
else {
  System.out.println("Grade B");	
}
 }
}
Output:
      Enter the marks of Physics 
      80
      Enter the marks of Chemistry 
      90
      Enter the marks of Maths 
      99
      Enter the marks of English 
      85
      Enter the marks of Computer 
      90
      Total marks in five subjects: 444.0
      My percentage: 88.8
      Grade A

2. Let’s take another example program where we will take a number as input from the user and check that number is even or odd.

For example, if the user enters a number 20 then it will display “Number 20 is even”. If the user enters 21, it will display “Number 21 is odd”. Let’s write code for it.

Program source code 2:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class.
  Scanner sc = new Scanner(System.in);
   
System.out.println("Enter a number:");
 int num = sc.nextInt();

if(num % 2 == 0){
 System.out.println("Number " +num+ " is even");	
}
else {
  System.out.println("Number " +num+" is odd");	
  }
 }
}
Output:
      Enter a number:
      22
      Number 22 is even

3. Let’s write a program to check whether a number is divisible with another number or not. Print appropriate message.


Program source code 3:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class.
   Scanner sc = new Scanner(System.in);
   
System.out.println("Enter the number that you want to divide:");
 int num1 = sc.nextInt();
System.out.println("Enter the divisor:");
 int num2 = sc.nextInt();
 
if(num1 % num2 == 0){
 System.out.println(num1+ " is divisible by " +num2);	
}
else {
  System.out.println(num1+ " is not divisible by " +num2);	
  }
 }
}
Output:
       Enter the number that you want to divide:
       30
       Enter the divisor:
       10
       30 is divisible by 10

4. Let’s create a java program to input a number and check whether it is a Buzz number or not. A number is said to be a buzz number when it ends with 7 or is divisible by 7.

Program source code 4:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class.
   Scanner sc = new Scanner(System.in);
   
System.out.println("Enter the number to check Buzz number:");
 int num = sc.nextInt();
 
if((num % 10 == 0) || (num % 7 == 0)){
 System.out.println(num+ " is a Buzz number ");	
}
else {
  System.out.println(num+ " is not a Buzz number");	
  }
 }
}
Output:
      Enter the number to check Buzz number:
      7777
      7777 is a Buzz number

Nested if statement in Java


If an “if statement” is declared inside another if,  or if-else statement, it is called nested if statement in Java. The inner if statement can also have another if statement.

In fact, there is no limit to the depth of the nesting. Nested if statements are very common in java programming.

The general syntax for Java nested if statements with an example are as follows:

if(condition){
  if(condition)
    statement1;
 }
else {
  statement2;
}
The following example is nested if statement: 
if (x > y) 
{
 if (y > z)
    System.out.println("x is greater than y and z"); // statement1.
}
else
  System.out.println("x is less than or equal to y"); // statement2.

In the above example, if x is greater than y and y is greater than z, statement1 will be executed. If x is greater than y but y is not greater than z then statement1 will not be executed. In this case, else part (statement2) will be executed.

5. Let’s take an example program based on Java nested if statements.

Program source code 5:

package javaProgram;
public class Test {
public static void main(String[] args) 
{ 	
int x = 20, y = 30, z = 10;
if(x == 20)
{
// First inner if statments inside outer if statement.
 if(y < 50) {
   System.out.println("ABC");	 
 }
// Second inner if-else statement inside outer if statement.
 if(z > 30)
  System.out.println("DEF");
 else
   System.out.println("PQR");	 
}
else {
  System.out.println("XYZ");	
}
 }
}
Output:
       ABC
       PQR

In this example program, since x is equal to 20 and y is less than 50, the result is displayed “ABC”. In the second inner if-else statements, z is not greater than 30, therefore, else part of it is executed and displayed “PQR”.

Suppose x is not equal to 20 in the above example. In this case, inner nested if statements will not be executed, and else part of outer if statement will be executed. The result will be only “XYZ”.

if-else if Ladder Statements in Java


if-else if ladder in Java is a multi-way decision structure that is used to decide among three or more actions.

The general syntax for if-else if ladder statements in Java are as follows:

if(condition)
   statement1;
else if(condition)
   statement2;
else if(condition)
   statement3;
   ...
else
   statement4;

In the above syntax, there can be multiple else if clauses and the last else clause is optional.

How if-else if Ladder works in Java


The flowchart diagram for Java if-else if ladder is shown in the below figure.

Java if-else if ladder flowchart diagram

if-else if ladder works in the following steps that are as follows:

1. The first specified condition evaluates to true. If the condition is true, statement1 is executed and the rest part of else if ladder is bypassed.

2. If the specified condition is false, the second if condition evaluates to true. If the second condition is true, statement2 is executed, and the rest part of the ladder is bypassed.

3. If the second condition is false, the third condition and the rest of the conditions (if required) are evaluated (or tested) until a condition is met or all of the conditions prove to be false.

4. If all of the conditions are false, the final else statement (i.e. statement4) associated with the top if statement will be executed.

5. The statement associated with final else acts as a default condition. That is, if all of the above conditional tests fail, the statement associated with the last else will be executed.

If there is no final else statement and none of the conditions is true, no action will take place.

Note: A condition is evaluated only when all of the conditions that come before it are false.

Example Program based on if-else if Ladder Statements


1. Let’s create a program to input the total marks of 5 subjects and calculate percentage and Grade according to percentage using Java if-else-if ladder.

Look at the following program source code to understand better.

Program source code 6:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class to take the input.
  Scanner sc = new Scanner(System.in);
 
System.out.println("Enter your total marks of 5 subjects:");
  int totalMarks = sc.nextInt();
   	
float myPer = totalMarks/5;
System.out.println("Percentage is: " +myPer);

if (myPer >= 90.0)
  System.out.print("Grade A");
else if (myPer >= 80.0)
  System.out.print("Grade B");
else if (myPer >= 70.0)
  System.out.print("Grade C");
else if (myPer >= 60.0)
  System.out.print("Grade D");
else
  System.out.print("Grade F");
 }
}
Output:
      Enter your total marks of 5 subjects:
      498
      Percentage is: 99.0
      Grade A

2. Let’s take an example program where we will take the age of user as input and find whether he is a child, adult, or senior on the basis of age. Using Java if-else-if ladder statements.

Program source code 6:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class to take the input.
  Scanner sc = new Scanner(System.in);
 
System.out.println("Enter your age:");
  int age = sc.nextInt();

if (age < 18)
  System.out.print("Child");
else if ((age >= 18) && (age <= 60))
  System.out.print("Adult");
else if (age <= 60)
  System.out.print("Senior");
else
  System.out.print("Invalid age");
 }
}
Output:
       Enter your age:
       20
       Adult

3. Let’s create a printing application program where we will take the number of copies to be printed as input from the user and then prints the price per copy and the total price for the printing copies.

The chart price to print the number of copies is given below:

  •  0 – 99 : $0.30 per copy
  • 100 – 499 :  $0.28 per copy
  • 500 – 799 : $0.27 per copy
  • 800 – 1000 : $0.26 per copy
  • over 1000 : $0.25 per copy

Look at the following program source code to understand better.

Program source code 7:

package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{ 	
// Create an object of Scanner class to take the input.
  Scanner sc = new Scanner(System.in);
 
System.out.println("Enter the number of copies to be printed:");
  int noOfCopies = sc.nextInt();

if(noOfCopies > 0 && noOfCopies < 100){
  double pricePerCopies = 0.30;
  System.out.println("Price per copy: "+"$" +pricePerCopies);
  double totalCost = noOfCopies * pricePerCopies;
  System.out.println("Total cost is "+"$" +totalCost);
}
else if(noOfCopies >= 100 && noOfCopies < 500){
   double pricePerCopies = 0.28;
   System.out.println("Price per copy: "+"$" +pricePerCopies);
   double totalCost = noOfCopies * pricePerCopies;
   System.out.println("Total cost is "+"$" +totalCost);
 }
else if(noOfCopies >= 500 && noOfCopies < 800){
   double pricePerCopies = 0.27;
   System.out.println("Price per copy: " +"$"+pricePerCopies);
   double totalCost = noOfCopies * pricePerCopies;
   System.out.println("Total cost is "+"$" +totalCost);
}
else if(noOfCopies >= 800 && noOfCopies < 1000){
   double pricePerCopies = 0.26;
   System.out.println("Price per copy: "+"$" +pricePerCopies);
   double totalCost = noOfCopies * pricePerCopies;
   System.out.println("Total cost is "+"$" +totalCost);
}
else {
   double pricePerCopies = 0.25;
   System.out.println("Price per copy: "+"$" +pricePerCopies);
   double totalCost = noOfCopies * pricePerCopies;
   System.out.println("Total cost is " +"$"+totalCost); 	
  }
 }
}
Output:
       Enter the number of copies to be printed:
       1151
       Price per copy: $0.25
       Total cost is $287.75

Hope that this tutorial has covered almost all the important points related to if-else statements in Java with example programs. I hope that you will have understood Java if-else-if ladder with suitable examples.
Thanks for reading!!!
Next ⇒ Loops in Java

⇐ Prev Next ⇒