Java Foundations · 8 min read · Beginner
Methods, Control Flow & Switch Expressions
Write typed Java methods, iterate with enhanced for-each loops, and return values directly from modern switch expressions.
What you'll learn
- Define static and instance methods with explicit return types
- Use Java's modern arrow switch expressions (->) with zero fall-through
- Loop cleanly over arrays with enhanced for-each loops
Modern Java (14+) introduced switch expressions using arrow syntax (->). Unlike legacy switch statements, arrow cases never fall through and can return a value directly into a variable.
Enhanced For-Each Loop
When you do not need the array index, for (int n : scores) is cleaner and eliminates index-out-of-bounds bugs.
Fill-in-the-Blank Exercise
Modern Switch Expression
Return a grade label using Java's arrow switch expression.
String label = (tier) {
case 1 "Gold";
case 2 -> "Silver";
default -> "Starter";
};Interactive Code Lab
JavaControlFlow.java
Expected OutputClick “Run Live” to compile with OpenJDK 21
94 -> A 82 -> B 75 -> C
Check Your Understanding
Score: 0 / 1
1. What is a major advantage of Java's arrow switch expression (->) over the classic switch statement?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.