You are here

If else program in Java

The if-else Java program uses if-else to execute statement(s) when a condition holds. Below is a simple application that explains the usage of if-else in Java programming language. In the program, a user input marks obtained in an exam, and we compare it with the minimum passing marks. We print an appropriate message on the screen based on whether the user passes the exam or not.

Java programming if else statement

// If else in Java code
import java.util.Scanner;

class IfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
   
    passingMarks = 40;
   
    Scanner input = new Scanner(System.in);
   
    System.out.println("Input marks scored by you");
   
    marksObtained = input.nextInt();
   
    if (marksObtained >= passingMarks) {
      System.out.println("You passed the exam.");
    }
    else {
      System.out.println("Unfortunately, you failed to pass the exam.");
    }
  }
}

Output of program:
Java if else program output

In this program, both if and else blocks contain only one statement, but we can execute as many of them as required.

Nested If Else statements

You can use nested if else which means that you can use if else statements in any if or else block.

import java.util.Scanner;
 
class NestedIfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
    char grade;
   
    passingMarks = 40;
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input marks scored by you");
 
    marksObtained = input.nextInt();
 
    if (marksObtained >= passingMarks) {
     
      if (marksObtained > 90)
        grade = 'A';
      else if (marksObtained > 75)
        grade = 'B';
      else if (marksObtained > 60)
        grade = 'C';
      else
        grade = 'D';
         
      System.out.println("You passed the exam and your grade is " + grade);
    }
    else {
      grade = 'F';
      System.out.println("You failed and your grade is " + grade);
    }
  }
}

Java nested if else program output