The main grammar features from Java 9 to Java 13 – summary

Sometimes it’s hard to keep up with the changes in the next versions of Java. For reminder I described main and the most useful features in Java grammar and standard library for each version between Java 9 and 13.

Grammar features in Java 9

New static methods for creating immutable collections:

List<Integer> list = List.of(1, 2, 3);
Set<Double> set = Set.of(1.2, 4.2);
Map<String, String> map = Map.of("key1", "value1", "key2", "value2");

Stream method in Optional class:

Stream<String> stream = Optional.of("sth").stream();

Private methods in interfaces:

public interface Example {
    
    default String method1() {
        return priv().toUpperCase();
    }

    default String method2() {
        return priv().toLowerCase();
    }
    
    private String priv() {
        return "Test";
    }
}

Grammar features in Java 10

Local variable type inference:

var list = List.of(1, 2, 3);

Non-argument method orElseThrow in Optional class:

var value = Optional.of(v).orElseThrow();

Grammar features in Java 11

The var syntax for lambda parameters (it’s required to apply annotation for arguments):

BiFunction<String, String, String> concat = (@Nullable var s1, @Nullable var s2) -> s1 + s2;

Helpful methods for read/write String from/to files:

var path = Files.writeString(path, "Test string");
System.out.println(Files.readString(path));

New methods in the String class: isBlank, repeat, lines:

System.out.println("".isBlank()); //true
System.out.println("\n".isBlank()); //true
System.out.println(" ".isBlank()); //true
System.out.println("test".isBlank()); //false
System.out.println("*".repeat(3)); //***
System.out.println("a\nb\nc".lines().count()); //3

Grammar features in Java 12

Switch expression:

var nextStage = switch(stage) {
    case "NEW" -> "OPEN";
    case "OPEN" -> "IN_PROGRESS";
    case "IN_PROGRESS" -> "DONE";
    default -> "ERROR";
};

Transform method in the String class:

var i = rawValue.transform(Integer::parseInt);

Grammar features in Java 13

Changes in switch expression:

var nextStage = switch(stage) {
	case "NEW":
		yield "OPEN";
	case "OPEN":
		yield "IN_PROGRESS";
	case "IN_PROGRESS":
		yield "DONE";
	default:
		yield "ERROR";
};

Multi-lines String:

var json = """
{
   "test": "value"
}
""";