Java Cheat Sheet: Control Structures

1. Conditional Statements

1.1 if Statement
if (condition) {
    // Code executes if condition is true
}
1.2 if-else Statement
if (condition) {
    // Executes if true
} else {
    // Executes if false
}
1.3 if-else if-else Ladder
if (condition1) {
    // Executes if condition1 is true
} else if (condition2) {
    // Executes if condition2 is true
} else {
    // Executes if none of the above conditions are true
}
1.4 Ternary Operator (Shortcut for if-else)
result = (condition) ? valueIfTrue : valueIfFalse;

2. Switch Statement

Used for selecting one of many code blocks to execute.

2.1 switch-case Syntax
switch (expression) {
    case value1:
        // Code block
        break;
    case value2:
        // Code block
        break;
    default:
        // Default code block
}
Notes:
  • expression must be of type byte, short, char, int, String, or enum.
  • break prevents fall-through.
  • default is optional.

3. Loops

3.1 while Loop
while (condition) {
    // Executes while condition is true
}
3.2 do-while Loop
do {
    // Executes at least once
} while (condition);
3.3 for Loop
for (initialization; condition; update) {
    // Executes until condition is false
}
3.4 Enhanced for Loop (for-each)
for (type var : arrayOrCollection) {
    // Iterates through elements
}

4. Branching Statements

4.1 break Statement
  • Exits the current loop or switch.
for (int i = 0; i < 10; i++) {
    if (i == 5) break;
}
4.2 continue Statement
  • Skips the current iteration and continues with the next.
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue;
    // Skips even numbers
}
4.3 return Statement
  • Exits from the current method and optionally returns a value.
return;         // For void methods
return value;   // For methods with return types

Tip: Loop Labels (Advanced)

Used with break and continue to affect outer loops.

outer:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (i == j) break outer;
    }
}