JAVA — CHAPTER 4

Control Statements: Part 2 · Concept Cheat Sheet
for do…while switch break / continue Logical Operators
1 for ITERATION STATEMENT
for (int i = 1; i <= 10; i++) { System.out.println(i); } // init; condition; increment — all in one line

3 parts of the header

  • Initializationint i = 1 (runs once)
  • Conditioni <= 10 (checked before each pass)
  • Incrementi++ (runs after each pass)

Best used for counter-controlled iteration — when you know how many times to loop.

2 CLASSIC for EXAMPLES

Sum even numbers 2–20

int total = 0; for (int n = 2; n <= 20; n += 2) { total += n; }

Compound interest

double amount = principal; for (int yr = 1; yr <= 10; yr++) { amount *= (1 + rate); System.out.printf("%d\t%.2f%n", yr, amount); }
3 do…while ITERATION STATEMENT
int count = 1; do { System.out.println(count); count++; } while (count <= 10);

Key difference vs while

The condition is tested after the body runs, so a do…while loop always executes at least once — useful for menus that must show before checking the exit condition.

4 switch MULTIPLE-SELECTION STATEMENT
switch (day) { case 1 -> System.out.println("Monday"); case 2 -> System.out.println("Tuesday"); default -> System.out.println("Other day"); }

Rules

  • Compares one value against several case labels
  • Classic syntax needs break; or execution "falls through"
  • Modern arrow syntax (->) doesn't fall through
  • default handles any unmatched value
5 break & continue

break

Immediately exits the loop (or switch) entirely.

for (int i=1;i<=10;i++){ if(i==5) break; System.out.println(i); } // prints 1 2 3 4

continue

Skips the rest of the current pass and moves to the next iteration.

for (int i=1;i<=10;i++){ if(i==5) continue; System.out.println(i); } // skips 5 only
6 LOGICAL OPERATORS
OperatorMeaning
&&AND — both must be true
||OR — at least one true
!NOT — reverses a boolean
^XOR — true only if exactly one is true

Short-circuit evaluation

&& and || stop evaluating as soon as the result is known — e.g. in a != 0 && b/a > 1, if a==0 the division never runs.

7 OBJECTS-NATURAL CASE STUDY: BigDecimal

Why not double for money?

double uses binary floating point, which can't represent many decimal fractions exactly — this causes tiny rounding errors that add up in financial calculations.

BigDecimal price = new BigDecimal("19.99"); BigDecimal qty = new BigDecimal("3"); BigDecimal total = price.multiply(qty);
8 METHOD REFERENCE TABLE — class BigDecimal
MethodPurpose
add(other)exact sum as a new BigDecimal
subtract(other)exact difference
multiply(other)exact product
divide(other, scale, mode)quotient with chosen decimal places & rounding mode
setScale(n, mode)rounds to n decimal places
compareTo(other)numeric comparison (ignores trailing zeros, unlike equals)