Java If-else Statement

The if statement runs a block of code only when a condition is true.

Forms of if

  • if
  • if-else
  • if-else-if ladder
  • nested if

Example: Grade Calculator

Java
int marks = 72;

if (marks >= 90) {
    System.out.println("Grade: A+");
} else if (marks >= 75) {
    System.out.println("Grade: A");
} else if (marks >= 60) {
    System.out.println("Grade: B");
} else if (marks >= 40) {
    System.out.println("Grade: C");
} else {
    System.out.println("Fail");
}
Grade: B

Example: Even or Odd

Java
int n = 7;
if (n % 2 == 0)
    System.out.println(n + " is even");
else
    System.out.println(n + " is odd");
7 is odd
Track your progress through the Java course