If else statement


Levels of difficulty: / perform operation:

Java if else program uses if else to execute statement(s) when a condition is fulfilled. Below is a simple program which explains the usage of if else in java programming language.

// 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.");
    }
  }
}




java if else program




Above program ask the user to enter marks obtained in exam and the input marks are compared against minimum passing marks. Appropriate message is printed on screen based on whether user passed the exam or not.

In the above code both if and else block contain only one statement but we can execute as many statements as required.