Careeroza
else and else if
if...else
Example
else runs when the condition is false.
public class Main {
public static void main(String[] args) {
int age = 16;
if (age >= 18) {
System.out.println("You can vote.");
} else {
System.out.println("You can vote in " + (18 - age) + " years.");
}
}
}Output
You can vote in 2 years.
else if Chains
Example
Conditions are checked from top to bottom. The first true one runs and the rest are skipped.
public class Main {
public static void main(String[] args) {
int[] allMarks = {95, 82, 67, 45, 30};
for (int marks : allMarks) {
String grade;
if (marks >= 90) {
grade = "A+";
} else if (marks >= 75) {
grade = "A";
} else if (marks >= 60) {
grade = "B";
} else if (marks >= 40) {
grade = "C";
} else {
grade = "Fail";
}
System.out.println(marks + " -> " + grade);
}
}
}Output
95 -> A+ 82 -> A 67 -> B 45 -> C 30 -> Fail
Tip: Order matters: put the most specific (highest) condition first. If marks >= 40 came first, 95 would get grade C.
Practice
Exercise: Write code that prints "Positive", "Negative" or "Zero" for an int n.
Show answer
if (n > 0) {
System.out.println("Positive");
} else if (n < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}