if, else if, else and the ternary operator
An if runs its block only when the condition in brackets is true. Unlike C or JavaScript, the condition must be a real boolean — Java will not treat 0, null or an empty string as false. Chain further checks with else if; the first true branch wins and the rest are skipped.
public class Main {
static String grade(int score) {
if (score >= 90) {
return "A";
} else if (score >= 75) {
return "B";
} else if (score >= 50) {
return "C";
} else {
return "F";
}
}
public static void main(String[] args) {
System.out.println(grade(95));
System.out.println(grade(75));
System.out.println(grade(49));
int stock = 0;
String label = stock > 0 ? "In stock" : "Sold out"; // ternary
System.out.println(label);
}
}A
B
F
Sold outSwap the order of the first two checks (>= 75 first). Now 95 prints B — order matters because the first match wins.
if (x) doThing(); without braces, but only the next single statement belongs to the if. Add a second indented line later and it runs unconditionally. Most team style guides require braces on every if, else, for and while.int cannot be converted to boolean — = instead of ==
public class Main {
public static void main(String[] args) {
int score = 70;
if (score = 100) {
System.out.println("Perfect");
}
}
}Main.java:4: error: incompatible types: int cannot be converted to boolean
if (score = 100) {
^
1 error= assigns; == compares. score = 100 is an assignment expression whose value is the int 100, and an if condition must be a boolean. In C this bug compiles and silently runs; Java's type checker catches it.
Use == to compare.
if (score == 100) {