SwadhyAI Notes

All Java notes

Java if...else

›Short versionOpen if you only have a minute.
  • if runs its body only when the condition is true. The condition has to be a boolean.
  • A semicolon right after if (condition) is an empty body. The next line is not inside the if.
  • else is the leftover path. It binds to the nearest if that does not already have one.
  • An else if chain stops at the first true condition. A broader test placed too early makes the later tests unreachable.
  • condition ? a : b picks a value. It is not a place for a block of statements.

An is the statement that takes one path or does not. The in parentheses is a boolean. The body is the next statement, and a pair of braces is how that next statement holds more than one line.

java
int age = 20;
if (age >= 18) {
    System.out.println("You are an adult");
}

With age at 20 the message prints. At 15 the block is skipped and the method continues after it. if (age >= 18); with a semicolon before the brace is a different program: the body is empty, and a following block runs whether the age test passed or not.

The other path, and the first test that wins

covers the values the if did not take. adds another test, and only one body in the chain runs.

java
int score = 85;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else if (score >= 70) {
    System.out.println("C");
} else {
    System.out.println("Try again");
}

85 fails the first test and passes the second, so the program prints B and does not look at the test for C. Reverse the tests, putting score >= 70 first, and 85 prints C. The later, stricter tests never see a value the early test already accepted. Write the narrow test first when the ranges overlap.

Choosing a value rather than a block

The operator is an expression. It belongs where a value belongs: the right side of an assignment, or an argument. Both results need a type the variable can hold.

java
int age = 20;
String label = age >= 18 ? "adult" : "minor";
System.out.println(label);

label is adult. The same choice as an if would declare the variable in both branches or assign it in both. The ternary does that in one expression. It gets worse as soon as either side grows a second statement. Use the chain above for that.

Several exact values of one int or one string, rather than overlapping ranges, are often clearer as a switch. The boolean values these conditions are made of are on Java booleans.

int score = 85; and a chain that tests score >= 70 before score >= 80. Which body runs?

The score >= 70 body runs. 85 makes that test true, and an else-if chain does not continue after the first success. The score >= 80 test is never evaluated. Put the higher threshold first if a score of 85 should take that path.