Skip to content

If–Else

This content is for Java. Switch to the latest version for up-to-date documentation.

If-else statements in Java allow you to test multiple conditions and execute different code blocks based on which condition is true.

if (condition1) {
// Code executed if condition1 is true
} else if (condition2) {
// Code executed if condition1 is false and condition2 is true
} else {
// Code executed if all conditions are false
}
int score = 85;
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
System.out.println("Grade: " + grade); // Output: Grade: B

You can nest if-else-if statements inside other if-else-if statements:

int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive alone.");
} else {
System.out.println("You need to get a license first.");
}
} else if (age >= 16) {
System.out.println("You can drive with an adult supervisor.");
} else {
System.out.println("You are too young to drive.");
}

You can combine multiple conditions using logical operators:

int temperature = 25;
boolean isRaining = false;
if (temperature > 30 && !isRaining) {
System.out.println("Great day for the beach!");
} else if (temperature > 20 || !isRaining) {
System.out.println("Good day for outdoor activities.");
} else {
System.out.println("Better stay indoors today.");
}
Built with passion by Ngineer Lab