Conditions
Conditions let a program choose which code to run. Without them a program would always do the same thing: show a discount to everyone or let anyone into the site without a password.
if
The code in curly braces after if runs only when the condition in parentheses is true. Code in curly braces is called a block:
void main() {
int age = 20;
if (age >= 18) {
IO.println("Access granted");
}
}Output:
Access grantedIn Java a condition must be a boolean. You cannot put a number or a string there — the compiler reports an error.
else
The else block runs when the condition is false. Exactly one of the two blocks always runs:
void main() {
int age = 15;
if (age >= 18) {
IO.println("Access granted");
} else {
IO.println("Access denied");
}
}Output:
Access deniedelse if
When there are more than two options, add else if between if and else. Conditions are checked top to bottom, and the first matching block runs — the rest are skipped:
void main() {
int score = 75;
if (score >= 90) {
IO.println("Excellent");
} else if (score >= 70) {
IO.println("Good");
} else {
IO.println("Needs work");
}
}Output:
GoodOrder matters: if the >= 70 check came first, a score of 95 would also get "Good".
Compound conditions
Several checks are combined with the logical operators && (and) and || (or). Java evaluates them in short-circuit fashion: if the answer is clear from the left side, the right side is not checked:
void main() {
int age = 25;
boolean hasTicket = true;
if (age >= 18 && hasTicket) {
IO.println("Enjoy the show");
}
}Output:
Enjoy the showThe ternary operator
When you need to pick one of two values, the ternary operator condition ? value1 : value2 is handy. It returns the first value if the condition is true and the second if it is false:
void main() {
int stock = 0;
String status = stock > 0 ? "In stock" : "Out of stock";
IO.println(status);
}Output:
Out of stockThe ternary operator is good for short choices. If there are more branches or several actions in them, write a regular if.
Common mistake
An extra semicolon after the condition cuts the block off from it. The if now controls the empty statement ;, and the block in braces always runs:
void main() {
int balance = 0;
if (balance > 100); {
IO.println("Purchase completed");
}
}Output:
Purchase completedThe compiler does not treat this as an error, so it is easy to miss. The { must come right after the condition's ).