You are here

Java if else program

Java if else program uses if else to execute statement(s) when a condition holds true. Below is a simple program which explains the usage of if else in Java programming language. In this program, a user inputs marks obtained in an exam, and it is compared with the minimum passing marks. An appropriate message is printed on the screen based on whether the user passed the exam or not.

Java programming if else statement

  1. // If else in Java code
  2. import java.util.Scanner;
  3.  
  4. class IfElse {
  5.   public static void main(String[] args) {
  6.     int marksObtained, passingMarks;
  7.    
  8.     passingMarks = 40;
  9.    
  10.     Scanner input = new Scanner(System.in);
  11.    
  12.     System.out.println("Input marks scored by you");
  13.    
  14.     marksObtained = input.nextInt();
  15.    
  16.     if (marksObtained >= passingMarks) {
  17.       System.out.println("You passed the exam.");
  18.     }
  19.     else {
  20.       System.out.println("Unfortunately, you failed to pass the exam.");
  21.     }
  22.   }
  23. }

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 statements 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.

  1. import java.util.Scanner;
  2.  
  3. class NestedIfElse {
  4.   public static void main(String[] args) {
  5.     int marksObtained, passingMarks;
  6.     char grade;
  7.    
  8.     passingMarks = 40;
  9.  
  10.     Scanner input = new Scanner(System.in);
  11.  
  12.     System.out.println("Input marks scored by you");
  13.  
  14.     marksObtained = input.nextInt();
  15.  
  16.     if (marksObtained >= passingMarks) {
  17.      
  18.       if (marksObtained > 90)
  19.         grade = 'A';
  20.       else if (marksObtained > 75)
  21.         grade = 'B';
  22.       else if (marksObtained > 60)
  23.         grade = 'C';
  24.       else
  25.         grade = 'D';
  26.          
  27.       System.out.println("You passed the exam and your grade is " + grade);
  28.     }
  29.     else {
  30.       grade = 'F';
  31.       System.out.println("You failed and your grade is " + grade);
  32.     }
  33.   }
  34. }

Java nested if else program output