Tutorial 1: if, else, and Boolean Expressions

Unit 3 · Decisions and Boolean logic

Objectives

A condition evaluates to true or false. Use == to compare primitive values, && for “and,” || for “or,” and ! for “not.” Use .equals for String content.

if (mark < 0 || mark > 100) {
    System.out.println("Invalid mark");
} else if (mark >= 50) {
    System.out.println("Pass");
} else {
    System.out.println("Try again");
}

Put the most specific invalid cases first. Braces make the controlled block explicit and prevent accidental bugs when code changes.

Practice

  1. Classify a number as negative, zero, or positive.
  2. Write a leap-year condition: divisible by 4 except centuries not divisible by 400.
  3. Create a login check using username.equals(...), not username == ....

Self-check

  1. Why does 1 < mark < 10 not work in Java?
  2. What is short-circuit evaluation?
  3. How would you simplify if (ready == true)?

Mastery task: Write a fare calculator with validated age and distance inputs, documenting each boundary decision.