Quiz
Warm-up from lesson 2-3: what is 10 % 3 in Java?
if and else
Branching is where programs earn their keep: is this password correct, does this cart qualify for free shipping, is this input even a number? Every rule a business has becomes an if somewhere. The Java version is the same idea as Python, different clothes: the condition goes in parentheses, the body goes in braces, and there is no colon. elif becomes else if.
if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else { System.out.println("C or below"); }
Comparisons are the usual >, >=, <, <=, ==, !=. Remember lesson 2-2: == is only for primitives. For Strings, write name.equals("Ada").
Logic operators change names from Python: and → &&, or → ||, not → !.
Code exercise · java
Run the grade classifier. Then change score to 93 and to 55 and check that each branch fires as you expect. Set it back to 87 to finish.
Combining conditions
&& and || short-circuit exactly like Python's and/or: Java stops evaluating as soon as the answer is known. That lets you write guards safely:
if (name != null && name.equals("Ada")) { ... }
If name is null (Java's None), the second half never runs, so no crash. Flip a boolean with !: !open means "not open".
One style rule worth adopting now: always write the braces, even for one-line bodies. Every style guide at every major company requires it.
Quiz
name is null. What happens on the line if (name.equals("Ada") && name != null) { ... }?
Code exercise · java
Your turn. A year is a leap year if it is divisible by 4 and not by 100, or divisible by 400. For year = 2024, print `2024 is a leap year`. If it were not one, print `2024 is not a leap year`. Use %, &&, and ||.