Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

pi/agent/skills/optional/java/java-pattern-switch/examples/jep-441.md

Raw
Rendered preview

JEP 441 examples

Source: https://openjdk.org/jeps/441

static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        case null      -> "null";
        default        -> obj.toString();
    };
}
static String testString(Object obj) {
    return switch (obj) {
        case String s when s.length() == 1 -> "short";
        case String s -> "long";
        default -> "not a string";
    };
}
# [JEP 441](https://openjdk.org/jeps/441) examples

Source: https://openjdk.org/jeps/441

```java
static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        case null      -> "null";
        default        -> obj.toString();
    };
}
```

```java
static String testString(Object obj) {
    return switch (obj) {
        case String s when s.length() == 1 -> "short";
        case String s -> "long";
        default -> "not a string";
    };
}
```