if and else
if
public class Main {
public static void main(String[] args) {
int temperature = 31;
if (temperature > 30) {
System.out.println("It's hot. Drink some water.");
}
System.out.println("Have a good day.");
}
}The condition goes in brackets and must be a boolean. The block in braces runs only when it's true; the program then carries on after it either way.
else and else if
public class Main {
public static void main(String[] args) {
int score = 74;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else if (score >= 60) {
grade = "C";
} else {
grade = "F";
}
System.out.println("Score " + score + " is grade " + grade);
}
}Conditions are checked from the top, and only the first true branch runs. The order matters: test score >= 60 first, and an A-grade score would stop there.
Combining conditions
public class Main {
public static void main(String[] args) {
int age = 16;
boolean withParent = true;
if (age >= 18 || withParent) {
System.out.println("You can watch the film.");
} else {
System.out.println("Sorry, not without a parent.");
}
int year = 2024;
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
System.out.println(year + " is a leap year: " + leap);
}
}Nested decisions
public class Main {
public static void main(String[] args) {
boolean loggedIn = true;
boolean isAdmin = false;
if (loggedIn) {
if (isAdmin) {
System.out.println("Welcome to the admin panel.");
} else {
System.out.println("Welcome back.");
}
} else {
System.out.println("Please sign in.");
}
}
}Nesting is fine a level or two deep. Deeper than that, combine conditions with &&, or move the logic into a method.
The ternary operator
public class Main {
public static void main(String[] args) {
int items = 1;
String label = items == 1 ? "item" : "items";
System.out.println(items + " " + label);
int a = 8, b = 13;
int bigger = a > b ? a : b;
System.out.println("Bigger: " + bigger);
}
}condition ? valueIfTrue : valueIfFalse chooses between two values. It's neat for short choices; for anything longer, an if is clearer.
Classic mistakes
public class Main {
public static void main(String[] args) {
String answer = new String("yes");
if (answer == "yes") {
System.out.println("== says they match");
}
if (answer.equals("yes")) {
System.out.println("equals says they match");
}
}
}Only the second message appears. Compare Strings with equals.
Two more to watch for:
- A stray semicolon.
if (score > 50);ends theifright there, and the block after it always runs. - Missing braces. Without braces, only the next single statement belongs to the
if. Add a second line later, and it runs every time. Always use braces.
The good news: if (x = 5) doesn't compile in Java, because an assignment isn't a boolean, so the classic C typo is caught for you.