Java12 Core Features

Java 12 introduced numerous new features, among which the most important include:

  • Switch Expressions: Java 12 introduces a new Switch expression that allows developers to return a value directly from within a single switch statement. This feature helps developers write code in a more concise and readable manner.

  • New Garbage Collectors: Java 12 introduces an experimental garbage collector known as Shenandoah. It is a low-latency garbage collector capable of handling very large heap sizes while maintaining extremely short pause times.

  • New String Methods: Java 12 introduced several new methods that make strings easier to use and understand. These methods include indent(), transform(), and describeConstable().

// Example usage of the describeConstable method (Java 12)
String str = "Hello, World!";
System.out.println(str.describeConstable()); // Output: String("Hello, World!")
  • New File Methods: Java 12 introduced new file methods that make file operations more convenient and flexible. These methods include Files.mismatch() and Files.tee().
// Example usage of Files.tee (Java 12)
Path path = Paths.get("input.txt");
List<Path> paths = List.of(path, "output.txt", "backup.txt");

try {
    // Create a temporary file to hold the original content before copying
    Path tempFile = Files.createTempFile(".txt");
    
    // Copy source files to the temporary file and destination files atomically
    Paths resultPaths = Files.tee(path, paths.subList(1, paths.size()));
} finally {
    if (Files.exists(tempFile)) {
        Files.delete(tempFile);
    }
}
  • CompletableFuture New Features: Java 12 introduced new CompletableFuture methods that make asynchronous programming easier and more direct. These methods include newIncompleteFuture(), completeAsync(), and completeOnTimeout().
// Example usage of CompletableFuture.newIncompleteFuture (Java 12)
CompletableFuture<Void> incomplete = CompletableFuture.newIncompleteFuture();

incomplete.complete(null); // Complete the future with null value
System.out.println(incomplete.isDone()); // Output: true
  • Restricted Default Ciphers: Java 12 restricts default encryption algorithms, making applications more secure.