Skip to content

Java Controls & Flow – Quick Reference

1. Conditional Statements

StatementSyntaxExample
ifif (condition) { ... }if (x > 0) { System.out.println("Positive"); }
if-elseif (condition) { ... } else { ... }if (x > 0) { ... } else { ... }
if-else-ifif (...) {...} else if (...) {...} else {...}if (score >= 90) { ... } else if (score >= 75) { ... } else { ... }
nested ifif (...) { if (...) {...} }if (x>0){ if(x%2==0){...} }
switchswitch(var){ case val: ...; break; default: ...; }switch(day){ case 1: ... break; default: ... }

2. Loops

LoopSyntaxExample
forfor(init; condition; update){...}for(int i=1;i<=5;i++){...}
whilewhile(condition){...}while(i<=5){ i++; }
do-whiledo{...} while(condition);do{ i++; } while(i<=5);
for-eachfor(type var : array/collection){...}for(int n: numbers){...}

3. Jump Statements

StatementUse
breakExit loop or switch immediately
continueSkip current iteration, continue next
returnExit method immediately

4. Ternary Operator

SyntaxExample
condition ? valueIfTrue : valueIfFalseString res = (x%2==0) ? "Even" : "Odd";

5. Flow Control Tips

  • Always use {} for clarity.
  • Avoid deep nesting; break into methods.
  • Use switch for discrete values.
  • Use for-each for collections when index not needed.
  • Name variables clearly for readability.

6. Quick Visual Example

java
for (int n : numbers) {
    if (n > 0) {
        System.out.println("Positive");
    } else if (n < 0) {
        System.out.println("Negative");
    } else {
        System.out.println("Zero");
    }
}

Memory Hooks:

  • if → condition check
  • switch → multi-choice
  • for / while / do-while → loops
  • break / continue / return → jump control
  • ?: → quick if-else

© 2023-2025 Maduranga Kannangara. Feel free to use or share this content. Attribution is appreciated but not required.