Making Choices with if and else
Teaching your program to decide
Real programs need to make decisions. Should a message be shown? Is a password correct? Did the player win the game? Java handles all of this with the if statement.
An if statement checks whether something is true, and only runs its block of code when that condition holds.
int age = 20;
if (age >= 18) {
System.out.println("You can vote.");
}
Because 20 is greater than or equal to 18, that message would be printed. If age had been 15, nothing would happen at all, since the condition would be false.
Adding an alternative with else
Often you want something to happen either way, just different things depending on the condition. That is where else comes in:
int age = 15;
if (age >= 18) {
System.out.println("You can vote.");
} else {
System.out.println("Not old enough to vote yet.");
}
Checking several conditions with else if
You can chain multiple checks together using else if, which Java reads from top to bottom until one condition matches:
int score = 72;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 70) {
System.out.println("Grade B");
} else {
System.out.println("Keep practicing");
}
Conditions are usually built with comparison operators such as == for is equal to, != for is not equal to, along with >, <, >=, and <=.
You can also combine conditions using &&, meaning and, and ||, meaning or, when a decision depends on more than one thing at once.
Once you are comfortable with if and else, your programs stop just running top to bottom and start actually reacting to the information they are given.
Quick check
Q1 Which symbol checks if two values are equal in Java?
Q2 What does an else block do?
Want to save your progress? It's free.
Create a free account