JAVA — CHAPTER 3

Control Statements: Part 1 · Concept Cheat Sheet
if / if…else while Counter vs Sentinel Compound & ++/-- Primitive Types
1 CONTROL STRUCTURES — THE BIG PICTURE

Sequence

Statements run one after another, top to bottom — the default flow.

Selection

Choose between paths: if, if…else, switch (Ch.4).

Iteration

Repeat a block: while, for (Ch.4), do…while (Ch.4).

2 if & if…else
if (grade >= 60) { System.out.println("Passed"); } else { System.out.println("Failed"); } // else if chain for multiple branches if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else grade = 'C';

Rules to remember

  • Single-selection = if only runs when true
  • Double-selection = if…else covers both cases
  • Braces {} group multiple statements into one block
  • Dangling-else: always brace your blocks to avoid ambiguity
3 while ITERATION — COUNTER vs SENTINEL CONTROL

Counter-controlled

Loop runs a known, fixed number of times using a counter variable.

int count = 1; while (count <= 10) { System.out.println(count); count++; }

Sentinel-controlled

Loop runs an unknown number of times, until a special "sentinel" input value ends it.

int num = input.nextInt(); while (num != -1) { // -1 is sentinel total += num; num = input.nextInt(); }
4 NESTED CONTROL STATEMENTS
int passes = 0, failures = 0, studentNum = 1; while (studentNum <= 10) { if (grade >= 60) { passes++; } else { failures++; } studentNum++; } // A selection statement living inside an iteration statement

Nesting = placing one control statement inside another (e.g., an if inside a while) to model more complex logic like pass/fail counters.

5 COMPOUND ASSIGNMENT & INCREMENT/DECREMENT
CompoundEquivalent
c += 3c = c + 3
c -= 3c = c - 3
c *= 3c = c * 3
c /= 3c = c / 3
c %= 3c = c % 3

++ and -- operators

  • Pre-increment ++c — increments first, then uses the value
  • Post-increment c++ — uses the value first, then increments
  • Same idea for --c and c--
6 PRIMITIVE TYPES & SUPER-SIZED INTEGERS

The 8 primitive types

  • byte, short, int, long — whole numbers
  • float, double — decimal numbers
  • char — single character
  • boolean — true / false

Why "super-sized" ints?

int/long have a max size. Java's BigInteger class (java.math) represents integers of virtually unlimited size for calculations that overflow primitives.

BigInteger a = new BigInteger("123456789012345678"); BigInteger b = a.multiply(a);
7 METHOD REFERENCE TABLE — class BigInteger
MethodPurpose
add(other)returns the sum as a new BigInteger
subtract(other)returns the difference
multiply(other)returns the product
divide(other)returns the quotient
mod(other)returns the remainder
compareTo(other)negative/zero/positive comparison result
toString()decimal String representation

Note: BigInteger objects are immutable — every operation returns a brand-new object rather than modifying the original.