Conditional Statements

beginner75 min

Conditional statements

When a condition is true, Java runs one block of code; when it is false, it can run another. That is how programs react to sensor values, gamepad input, and mode flags.

Basic if statement

Code Blocks and Indentation

The body of an if sits inside curly braces { }. Indent the body by four spaces so the structure is easy to read.

Indentation

Comparison operators

  • > - Greater than
  • >= - Greater than or equal to
  • < - Less than
  • <= - Less than or equal to
  • == - Equal to
  • != - Not equal to

Comparison examples

Else Statements

else runs when the if condition is false.

If-else example

else if

Chain else if to test several conditions in order. The first true branch runs; the rest are skipped.

Multiple conditions

Order of execution

  • Conditions are checked from top to bottom.
  • Only the first true branch runs.
  • Put more specific tests before general ones (see FizzBuzz example below).

Execution order example

Comparing Strings

For String values, use .equals() to compare characters. == checks whether two references point to the same object, which is not what you want for user input or telemetry text.

String comparison

Logical Operators

Use && (AND), || (OR), and ! (NOT) to combine boolean expressions.

Logical operators

  • && - AND (both conditions must be true)
  • || - OR (at least one condition must be true)
  • ! - NOT (reverses the boolean value)

Examples:

Logical operator truth table

Try It Yourself:

Exercise 1: Conditional Logic Practice

  • Create a robot battery status checker with multiple levels
  • Write a sensor range validator with proper error handling
  • Implement a game mode selector using string comparisons
  • Build a complex safety system using logical operators
Practice writing conditional statements for various scenarios: