mindixx
mindixx

Reference · module 2

Decisions and loops

Everything this module explains, on one page.

if and else

Run code only when a condition is true.

  • if (age >= 18) { ... } runs the block only when the condition in brackets is true. The brackets are required, and braces group the statements that belong to the if.
  • else if checks another condition, and else catches everything left. Java checks them top to bottom and runs only the first block whose condition is true.
  • && means and, || means or, ! means not: if (age >= 18 && hasTicket). Comparison uses ==, and a single = is assignment, which does not compile in a condition with ints.

The mistake you are about to make

if (x = 5)

if (x == 5)

= reads as equals in maths, so it goes into the condition. In Java = assigns a value; comparing needs ==.

for and while

Repeat code a set number of times or while a condition holds.

  • for (int i = 0; i < 3; i++) { ... } has three parts: a start, a condition checked before each round, and a step. This loop runs with i = 0, 1 and 2.
  • while (condition) { ... } repeats as long as the condition is true. Something inside must change the condition, or the loop never ends.
  • The classic slip is one round too many or too few. i < 3 runs three times from 0; i <= 3 runs four times. Count the rounds before trusting a loop.

The mistake you are about to make

for (int i = 0; i <= 5; i++) // 5 times

for (int i = 0; i < 5; i++)

Up to 5 sounds like <= 5. Starting from 0, <= 5 gives 0 to 5, which is six rounds.

switch

Choose between many fixed values with switch.

  • A switch picks a branch by value. The modern form uses arrows: switch (day) { case 6, 7 -> System.out.println("weekend"); default -> System.out.println("workday"); }
  • default runs when no case matches, like the final else. One case can list several values separated by commas.
  • switch also works on strings and can produce a value: String size = switch (code) { case "S" -> "small"; case "L" -> "large"; default -> "medium"; };

The mistake you are about to make

case 6: ... case 7: ... (no break)

case 6, 7 -> ...

The old colon form looks the same as arrows. Without break it falls through into the next case; the arrow form never falls through.

Back to the map