Java If Else
Programs become useful the moment they can make decisions. Java's if...else statements let your code choose between different paths depending on whether a condition is true or false. In this lesson you will learn the four conditional keywords, how to combine them, and the compact shortcut Java gives you for simple choices.
Making decisions with conditions
A condition is any expression that evaluates to a boolean, meaning it results in either true or false. Java gives you four building blocks to react to those conditions. You use if to run a block only when something is true, else to provide a fallback, else if to test extra possibilities, and you can nest these to describe more detailed logic.
- if - runs a block of code when its condition is true.
- else - runs a block when the if condition (and any else if conditions) turned out to be false.
- else if - tests a new condition when the previous one was false.
- The ternary operator ( ? : ) - a one-line shortcut that picks between two values.
The if statement
The simplest form is a single if. You place a boolean condition in parentheses, and the code inside the curly braces runs only when that condition is true. If it is false, Java skips the block entirely and moves on.
A basic if statement
public class Main {
public static void main(String[] args) {
int temperature = 32;
if (temperature > 30) {
System.out.println("It is a hot day, stay hydrated.");
}
System.out.println("Program finished.");
}
}
// Output:
// It is a hot day, stay hydrated.
// Program finished.Adding else and else if
Most real decisions need more than one branch. Add an else to describe what should happen when the condition is false, and chain else if branches in between to test additional conditions in order. Java checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest.
Grading with else if
public class Main {
public static void main(String[] args) {
int score = 78;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 75) {
System.out.println("Grade: B");
} else if (score >= 60) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
}
}
// Output:
// Grade: BThe ternary shortcut
When you only need to choose between two values based on one condition, the ternary operator keeps things short. It reads as: condition ? valueIfTrue : valueIfFalse. It is an expression, so it produces a value you can store in a variable or print directly.
Choosing a value with the ternary operator
public class Main {
public static void main(String[] args) {
int age = 20;
String access = (age >= 18) ? "Allowed" : "Denied";
System.out.println(access);
}
}
// Output:
// AllowedExercise: Java If...Else
What happens if an if statement's condition is false and there is no else branch?