Java If-else Statement
The if statement runs a block of code only when a condition is true.
Forms of if
ifif-elseif-else-ifladder- nested
if
Example: Grade Calculator
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
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