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.

Syntax of If Else Statement


A two-way if else statement in Java routes program execution through two different paths based on whether the condition is true or false. The syntax for using two-way if-else statement in java is as follows:

if(boolean expression or condition) {
    statement1; // statement to be executed if the condition is true.
}
else {
   statement2; // statement to be executed if the condition is false.
}

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 either true or false.

The else clause is an optional part. It means that we can omit else clause part if not required. You can follow this convention in all control statements in Java.

Flowchart Diagram of If-else Statement


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

Java If-else flowchrat diagram

How If else Statement Works in Java


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

If the condition specified after is true, then statement1 will execute. If the condition is false, statement2 (if it exists) will execute. In no case will both statements execute simultaneously. 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, you can omit the braces if there is only one statement within the block. We can also use conditional operator (?:) instead of if-else statement. Consider the following example code.

System.out.println(passMarks >= 40 ? "Pass" : "Fail");

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 of Java If else Statements


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


Example 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();
 
// Find out the total marks of five subjects.
   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);

// Checking percentage to find grade using if else statement.
   if(myPer >= 80) { 
    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

Let’s consider 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.

Example 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();

// Checking the even or odd using if-else statement. 
   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

Let’s take an example program to check whether a number is divisible with another number or not. Print appropriate message.

Example 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();
 
// Checking the divisibility of number using if else statement.
   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

Let’s take an example program in which we will take a number as an input 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.

Example 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();
 
// Checking buzz number using if else statement.
   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 Statements in Java


If an “if statement” is declared inside another if,  or if-else statement, it is called nested if statements 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 using Java nested if statements with an example is as follows:

// Outer if statement.
   if(condition) 
  {
// Inner if statement defined in outer if else statement.
    if(condition)
      statement1;
  }
// Else part of outer if statement.
   else {
      statement2;
   }

For example:

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 execute. If x is greater than y but y is not greater than z then statement1 will not execute. In this case, else part (statement2) will execute.


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

Example 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 statement 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");	 
   }
// Outer else block.
   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 will display “ABC”. In the second inner if-else statements, z is not greater than 30, therefore, else part of it executes and will display “PQR”.

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

If else If Ladder Statements in Java


The 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 will execute and the rest part of else if ladder will bypass.

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

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 of If else If Ladder Statements


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

Example 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);

// Applying if-else if ladder statements.
   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

Let’s consider 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.

Example 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 your age:");
   int age = sc.nextInt();

// Applying if else if ladder statements.
   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

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 example code to understand better.

Example 8:

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

FAQs on Google Search

Q1: Can we use multiple “else” blocks in an if-else statement?

A: No, an if-else statement can have only one “else” block, which is executed when all previous conditions are false.

Q2: What happens if no condition in the if-else ladder is true?

A: In such cases, the code inside the “else” block will execute by default.

Q3: Is there any limit to using “else-if” conditions many times?

A: There is no specific limit, but many “else-if” conditions can lead to code complexity and reduced readability.

Q4: Can we use the “if-else” statement to compare strings?

A: Yes, we can use “if-else” statement to compare strings using the equals() method or other string comparison techniques in Java.