Java versions
versions4Java9To11Features
- Path
- pkg2versions/versions4Java9To11Features.java
- Package
- pkg2versions
- Study order
- 4
- Run
- Single-file source launch
- Command
- java pkg2versions/versions4Java9To11Features.java
- Version in the filename
- Java 9–11
- Example
- Cumulative Java 9–11 example
- Requires
- Java 11
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg2versions;2 3/*4 * versions4Java9To11Features.java5 * ----------------------6 * Cumulative Java 9-11 example. The whole file requires Java 11.7 * It is not a Java 9 or Java 10 program: var is Java 10, and the8 * String methods below are Java 11. Collection uses Collectors.toList(),9 * which is Java 8. It does not call the Java 16 Stream toList method.10 *11 * FEATURES & WHY:12 * Java 9 : Module system (JPMS), collection factory methods (List.of),13 * private interface methods, Stream.takeWhile/dropWhile.14 * Java 10 : `var` local variable type inference.15 * Java 11 : new String methods (strip, isBlank, lines, repeat),16 * Files.readString/writeString, the standard HttpClient, run .java directly.17 * (Java 11 is an LTS release.)18 */19import java.util.*;20import java.util.stream.*;21 22public class versions4Java9To11Features {23 public static void main(String[] args) {24 // Java 9: immutable collection factories25 List<Integer> list = List.of(1, 2, 3);26 Map<String, Integer> map = Map.of("a", 1, "b", 2);27 Set<String> set = Set.of("x", "y");28 System.out.println("factories: " + list + " " + map + " " + set);29 30 // Java 9: takeWhile / dropWhile31 List<Integer> taken = Stream.of(1, 2, 3, 4, 1).takeWhile(x -> x < 4).collect(Collectors.toList());32 List<Integer> dropped = Stream.of(1, 2, 3, 4, 1).dropWhile(x -> x < 4).collect(Collectors.toList());33 System.out.println("takeWhile<4: " + taken + " dropWhile<4: " + dropped);34 35 // Java 10: var36 var greeting = "hello";37 var numbers = new ArrayList<Integer>();38 numbers.add(42);39 System.out.println("var: " + greeting + " " + numbers);40 41 // Java 11: String methods42 System.out.println("isBlank: " + " ".isBlank());43 System.out.println("strip: [" + " hi ".strip() + "]");44 System.out.println("repeat: " + "=".repeat(10));45 "line1\nline2\nline3".lines().forEach(l -> System.out.println(" " + l));46 }47}