The New Java

by: ‘Mohammad Noor’ AbuKhleif
noor.guru

Java Versions

VersionRelease DataNotesImportant New Features
JDK 1.0January 1996
J2SE 5.0September 20045 releases in 8 yearsEnhanced For Loop, Generics, Enums, Autoboxing
Java SE 8 LTSMarch 2014Functional Programming (Lambdas, Streams, …) & static and default methods in interfaces
VersionRelease DataNotesImportant New Features
Java SE 9September 20174 releases in 13 yearsModularization (Java Platform Module System) & JShell
Java SE 10 (18.3)March 2018The new (time-based) versioning system!Local Variable Type Inference
Java SE 11 (18.9) LTSSeptember 2018First new Long Term Support Version
VersionRelease DataNotesImportant New Features
Java SE 12 (19.3)March 2019
Java SE 13 (19.9)September 2019
Java SE 14 (20.3)March 2020switch expressions
VersionRelease DataNotesImportant New Features
Java SE 15 (20.9)September 2020Text blocks
Java SE 16 (21.3)March 2021Latest Versionrecord classes
Java SE 17 (21.9) LTSSeptember 2021The next LTS version

Java 9

JShell

  • The Java Shell tool (JShell) is an interactive tool for learning the Java programming language and prototyping Java code.
  • JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results.
  • The tool is run from the command line.
  • Using JShell, you can enter program elements one at a time, immediately see the result, and make adjustments as needed.
  • You can use Java to write scripts!

Modules

(Java 9 Platform Module System - JPMS)
  • Modularity adds a higher level of aggregation above packages.

  • The key new language element is the module:

    • a uniquely named, reusable group of related packages, as well as resources (such as images and XML files) and a module descriptor specifying.

Private interface Methods

public interface MyInterface {

    void normalInterfaceMethod();

    default void interfaceMethodWithDefault() {  init(); }

    default void anotherDefaultMethod() { init(); }

    // This method is not part of the public API exposed by MyInterface
    private void init() { System.out.println("Initializing"); }
    
    // This method is not part of the public API exposed by MyInterface
    private static void doSomething() { System.out.println("Doing Something!"); }
}

Collection Factory Methods


Set<Integer> ints = Set.of(1, 2, 3);
List<String> strings = List.of("first", "second");

More Resources

Java 10

Local Variable Type Inference

String message1 = "Good bye, Java 9";

var message2 = "Hello, Java 10";
Map<Integer, String> map = new HashMap<>();

var idToNameMap = new HashMap<Integer, String>();
  • Note that this feature is available only for local variables with the initializer.
    • It cannot be used for member variables, method parameters, return types, etc.

    • The initializer is required as without which compiler won’t be able to infer the type.

It is not always a good idea to use a var.

var result = obj.prcoess();
    
var x = emp.getProjects.stream()
    .findFirst()
    .map(String::length)
    .orElse(0);

Container Awareness

  • JVMs are now aware of being run in a Docker container and will extract container-specific configuration instead of querying the operating system itself.

    • This applies to data like the number of CPUs and total memory that have been allocated to the container.
  • This support is only available for Linux-based platforms

copyOf()

(Create Unmodifiable Collections)
  • java.util.List, java.util.Map and java.util.Set each got a new static method copyOf(#collection#).
  • It returns the unmodifiable copy of the given Collection.
List<Integer> copyList = List.copyOf(someIntList);
  • Any attempt to modify such a collection would result in java.lang.UnsupportedOperationException runtime exception.

toUnmodifiable###()

  • java.util.stream.Collectors get additional methods to collect a Stream into an unmodifiable List, Map or Set.
List<Integer> evenList = someIntList.stream()
    .filter(i -> i % 2 == 0)
    .collect(Collectors.toUnmodifiableList());
  • Any attempt to modify such a collection would result in java.lang.UnsupportedOperationException runtime exception.

Time-Based Release Versioning

  • A new Java release every six months starting from this version (Java 10 / 18.3).
    • These are called feature releases and are expected to contain at least one significant feature.
    • Support for the feature release will last only for six months, i.e., until next feature release.
  • Long-term support release will be marked as LTS.
    • Support for such release will be for three years.
    • Java 11 (18.9) will be an LTS release.

More Resources

Java 11

The Current LTS Version

Oracle vs. Open JDK

  • Java 10 was the last free Oracle JDK release that we could use commercially without a license.
  • Starting with Java 11, there’s no free long-term support (LTS) from Oracle.
  • Open JDK releases are still free and open-source.

New String Methods

  • isBlank: Empty Strings and Strings with only white spaces are treated as blank.
System.out.println(" ".isBlank());      // true
System.out.println("Noor".isBlank());   // false
System.out.println("".isBlank());       // true
  • lines: Returns a stream of strings, which is a collection of all substrings split by lines.
    • Can be very useful when reading from files.
String str = "First\nSecond\nThird"; 
System.out.println(str);
System.out.println("---");
System.out.println(str.lines().collect(Collectors.toList()));

This will result in the following output:

First
Second
Third
---
[First, Second, Third]
  • strip: Removes the white space from both, beginning, and the end of string.
  • stripLeading: Removes the white space from the beginning of string.
  • stripTrailing: Removes the white space from the end of string.
String str = "  Noor  ";
System.out.println("|" + str                  + "|"); // |  Noor  |
System.out.println("|" + str.strip()          + "|"); // |Noor|
System.out.println("|" + str.stripLeading()   + "|"); // |Noor  |
System.out.println("|" + str.stripTrailing()  + "|"); // |  Noor|
  • repeat: Returns a string whose value is the concatenation of this string repeated count times.
System.out.println("=".repeat(10));   // ==========

New File Methods

  • We can use the new readString and writeString static methods from the Files class.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class StringMethods {
    public static void main(String[] args) throws IOException {
        Path filePath = Files.createFile(Path.of("file.txt"));
        
        // writeString: will wtite a string to the file
        Files.writeString(filePath, "Sample text");
        
        // readString: will read the file as a string
        String fileContent = Files.readString(filePath);
        
        System.out.println(fileContent);  // Sample text
    }
}

The not Predicate Method

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class StringMethods {
    public static void main(String[] args) {
        List<String> sampleList = List.of("Hello", "\n \n", "World", " ", "");

        // Java 10 and before
        List<String> notEmptyStrings10 = sampleList.stream()
                .filter(s -> !s.isBlank())
                .collect(Collectors.toList());
        System.out.println(notEmptyStrings10);  // [Hello, World]

        // Java 11
        List<String> notEmptyStrings11 = sampleList.stream()
                .filter(Predicate.not(String::isBlank))
                .collect(Collectors.toList());
        System.out.println(notEmptyStrings11);  // [Hello, World]
    }
}

More Resources

Java 12

New String Methods

  • indent: Adjusts the indentation of each line of this string based on the value of n.
String text = "Hello World!\nThis is Noor.";
System.out.println(text.indent(4));
    Hello World!
    This is Noor.

There are some other new methods, like transform.

File::mismatch Method

  • Finds and returns the position of the first mismatched byte in the content of two files, or -1L if there is no mismatch.
  • The position will be in the inclusive range of 0L up to the size (in bytes) of the smaller file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class StringMethods {
    public static void main(String[] args) throws IOException {
        Path filePath1 = Files.createFile(Path.of("file1.txt"));
        Path filePath2 = Files.createFile(Path.of("file2.txt"));
        Path filePath3 = Files.createFile(Path.of("file3.txt"));
        Files.writeString(filePath1, "Hello world from Noor");
        Files.writeString(filePath2, "Hello world from Noor");
        Files.writeString(filePath3, "Hello world from noor");

        System.out.println(Files.mismatch(filePath1, filePath2));   // -1
        System.out.println(Files.mismatch(filePath1, filePath3));   // 17
    }
}

More Resources

Java 13

Not a lot of finalized new features are introduced in Java 13.

More Resources