Core Java
core5ControlStatements
- Path
- pkg1core/core5ControlStatements.java
- Package
- pkg1core
- Study order
- 4
- Run
- Single-file source launch
- Command
- java pkg1core/core5ControlStatements.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core5ControlStatements.java5 * ----------------------6 * if / else if / else, classic switch, modern switch expressions, and7 * pattern matching for switch (Java 21).8 *9 * EXPLANATION:10 * - switch EXPRESSIONS (->) return a value and don't fall through.11 * - Pattern matching lets switch branch on the runtime TYPE of an object.12 */13public class core5ControlStatements {14 sealed interface Shape permits Circle, Rectangle {}15 record Circle(double r) implements Shape {}16 record Rectangle(double w, double h) implements Shape {}17 18 public static void main(String[] args) {19 int score = 82;20 21 // if / else if / else22 String grade;23 if (score >= 90) grade = "A";24 else if (score >= 80) grade = "B";25 else if (score >= 70) grade = "C";26 else grade = "F";27 System.out.println("Grade: " + grade);28 29 // Classic switch (statement)30 int day = 3;31 switch (day) {32 case 1: System.out.println("Monday"); break;33 case 3: System.out.println("Wednesday"); break;34 default: System.out.println("Other day");35 }36 37 // Switch EXPRESSION with arrow and yield38 String type = switch (day) {39 case 1, 2, 3, 4, 5 -> "Weekday";40 case 6, 7 -> "Weekend";41 default -> {42 yield "Invalid"; // yield returns from a block43 }44 };45 System.out.println("Day type: " + type);46 47 // Pattern matching for switch (Java 21) + guarded patterns48 for (Shape sh : new Shape[]{ new Circle(2), new Rectangle(3, 4) }) {49 double area = switch (sh) {50 case Circle c -> Math.PI * c.r() * c.r();51 case Rectangle r when r.w() == r.h() -> r.w() * r.w(); // guard52 case Rectangle r -> r.w() * r.h();53 };54 System.out.printf("Area of %s = %.2f%n", sh, area);55 }56 57 // instanceof pattern matching (binds the variable)58 Object o = "hello";59 if (o instanceof String str && str.length() > 3) {60 System.out.println("String of length " + str.length());61 }62 }63}