4.5 Code block, conditions

This lesson refines the if/else pattern. We start from if (value < 10): when the test is true, the block that follows runs and prints the value. We add an else branch (the French "sinon") that prints "the value is not less than 10". With the value set to 11, the first test fails so the program jumps straight to the else block.

If we flip the condition to if (value >= 10) and rerun the program, the first branch is taken and the else is ignored. That is the classic two-branch shape of an if/else: only one of the two blocks is executed.

Going further with else if

  • if (value > 10) handles the strictly greater case.
  • else if (value == 10) handles the exact equality.
  • else covers everything else.

With the value set to 10, the first test (> 10) is false, so execution moves on to the else if (value == 10) branch, which is true, and prints the matching message. The final else is only reached when none of the previous conditions are validated. In the next lessons we will keep playing with if and explore boolean operators to combine several conditions inside one test.

Summary

This lesson introduces conditional statements in Java, covering how if, else if, and else blocks control program flow based on different conditions. The video demonstrates evaluating conditions using comparison operators (greater than, less than, equal to) and explains how only the first true condition executes while others are skipped.

Key points

  • Conditional statements (if, else if, else) control which code block executes based on whether its condition is true or false
  • Only the first condition that evaluates to true is executed; remaining conditions are bypassed
  • Use comparison operators to test conditions: > (greater than), < (less than), == (equal to)
  • The else block serves as a fallback that executes if no preceding conditions are true
  • Multiple conditions can be chained using if/else if/else structure for complex decision logic
  • Each condition is tested in order; once one is satisfied, the program exits the entire conditional structure

FAQ

What happens when multiple conditions are true?

Only the first true condition executes. Once a condition is satisfied, the program skips all remaining else if and else blocks and continues after the entire conditional structure.

What is the difference between else if and else?

else if allows you to test another specific condition before executing; else is the final fallback that executes unconditionally if no previous conditions are true.

How do comparison operators work in conditional statements?

Comparison operators (>, <, ==) evaluate whether a statement is true or false. The code block only executes if the comparison returns true.