Nearby lessons

18 of 125

Java - Decision Making

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

Decision Making is a core concept of the Java language. This lesson explains Java Statements (Control Flow) and if — The Initialization Trap with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Java Statements (Control Flow)

Statements decide the flow of the program — which code runs, when, and how many times. There are two families:

  • Decision making (selection) — if, if-else, if-else if, switch.
  • Looping (iteration) — for, while, do-while.

Plus two jumping statements: break and continue.

if — The Initialization Trap

Local variables have no default value. If a variable might remain unassigned, the compiler gives an error: variable j might not have been initialized.

Fix: give an else block, or an else if with a final else, or initialise j when declaring. The compiler must be sure that every path assigns a value.

Example02
JCode Cell
1class IfTrap {
2 public static void main(String[] args) {
3 int i = 10, j;
4 if (i == 10) {
5 j = 20;
6 }
7 System.out.println(j); // ERROR! j might not be initialized
8 }
9}

if — The Initialization Trap

Constant Expressions vs Variable Expressions

A constant expression contains only constants (including final variables). The compiler evaluates it — it already knows the answer. Example: if (10 == 10), if (true), if (finalVar == 10).

A variable expression contains at least one ordinary variable. The JVM evaluates it at run time. Example: if (i == 10) where i is a normal variable.

This explains why if (true) { j = 20; } System.out.println(j); compiles fine (the compiler knows the block always runs) — the compiler replaces final variables with their values first, a trick called constant folding.

Example03
JCode Cell
1int i = 10, j;
2if (i == 10) { j = 20; } else { j = 30; } // OK - both paths assign
3System.out.println(j); // 20
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1