Java language extensions

Java 15

https://www.oracle.com/java/technologies/javase/15-relnote-issues.html

Records Preview (JEP 384)

// old way using Lombok
@Data
public final class Car14 {
    @NotNull
    private final String name;
    private final int hp;
    public Car14(String name, int hp) {
        this.name = name;
        this.hp = hp;
        if (this.hp < 100) {
            throw new IllegalArgumentException("HP has to be bigger than 100.");
        }
    }
}

// new Java 15 record preview
@SuppressWarnings("preview")
public record Car15(@NotNull String name, int hp) {
    public Car15 {
        if (hp < 100) {
            throw new IllegalArgumentException("HP has to be bigger than 100.");
        }
    }
}

Example on Github

Text Blocks (JEP 378)

final String textBlockString = 
    """
    Hello cool
        text block <b>including</b> also HTML "tags".
    Json: {"name":"F1","hp":100
    """;

Example on Github

Pattern Matching Type Checks (JEP 375)

// pre Java 15
final Object type = Long.valueOf(4L);
if (type instanceof Long && ((Long)type).longValue() > 3) {
    Long longValue = (Long)type;
    System.out.println(longValue);
}

// new Java 15
final Object type = Long.valueOf(4L);
if (type instanceof Long longValue && longValue.longValue() > 3) {
    System.out.println(longValue);
}

Example on Github

Other Java 15 language changes

  • Nashorn JavaScript Engine removed

Java 14

https://www.oracle.com/java/technologies/javase/14-relnote-issues.html

Switch Expressions (JEP 361)

// old
Strategy preJava14;
switch (movement) {
    case "up":
    case "w": 
        preJava14 = Strategy.UP;
        break;
    case "down":
    case "s":
        preJava14 = Strategy.DOWN;
        break;
    case "d":
        preJava14 = Strategy.RIGHT;
        break;
    case "left":
    case "a": {
            System.out.println("going left ...");
            preJava14 = Strategy.LEFT;
        }
        break;
    default: throw new IllegalArgumentException("Unexpected movement: " + movement);
}
System.out.println("Java 14: " + preJava14);

// new Java 14
final Strategy movementStrategy = switch (movement) {
    case "up", "w" -> Strategy.UP;
    case "down", "s" -> Strategy.DOWN;
    case "d" -> Strategy.RIGHT;
    case "left", "a" -> {
        System.out.println("going left ...");
        yield Strategy.LEFT;
    }
    default -> throw new IllegalArgumentException("Unexpected movement: " + movement);
};

Java 13

https://www.oracle.com/java/technologies/javase/13-relnote-issues.html

Java 12

https://www.oracle.com/java/technologies/javase/12-relnote-issues.html

Paul Sterl has written 52 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>