From Java 9 to Java 14. What’s new? (Part 1)

Java used to have a new version every 3 to 4 years until Java 9 release. After Java 9 we have a 6 months cadence for releasing a new Java version. Since September 2017 until now, we have had 6 different Java versions, with an LTS version (Java 11). At this moment, the latest Java 14 is the latest version. So, it’s not easy to keep in mind all the new features that are being added to Java with every release. The goal of this article is to provide a summary of the main features that a Java Developer should keep in mind from Java 9 to Java 14.

In order to organize better all this information, this post will be split into 3 parts:
– Part 1 (Java 9 to Java 11)
Part 2 (Java 12 to Java 14)
Part 3 (A comparison between Java 8 code to Java 14)

Java 9

The first short term release of this new schema of versioning. Most of its features were related to the optimization of the Garbage Collector and deprecating legacy API. However, a couple of features can be highlighted in this version.

– JShell (REPL)

It is an interactive Java Shell tool, it allows us to execute Java code from the shell and shows output immediately. JShell is a REPL (Read Evaluate Print Loop) tool and runs from the command line. Some other languages provide this tool and Java was lacking it, but not anymore.

– Collection Factory Methods

Oh! Yes! This feature has waited for a long time. Finally, we can create Collections with values in one line using the .of(T ...) method of any collection (List, ArrayList, Set, and more).

List<String> list = List.of("Java","JavaFX","Java EE","Hibernate","JSP");

– Java Modules

A module is a new way of grouping code, data and some resources, adding a higher level of aggregation above packages. Every module describes which packages are exposed and which packages of other modules your application depends on. In modules, only explicitly exported public classes can be used from other modules.

In order to convert our Java jar project into a Java module project, we only need to add a module-info.java file.

module com.myapp.mymodule {
	requires other.module.dependency;
	exports some.package.inthe.application;
	exports another.package.inthe.application;
}

If you to learn more details about Java Modules I wrote an article some time ago here.

Java 10

Java 10 was a short term release, most of its changes pointed to improvements in memory management, garbage collection, and removing some old APIs from the core. From the developer perspective, the great feature is the “Local Variable Type Inference“.

– Local Variable Type Inference

Now the compiler can infer the type of a variable with the value the is assigned in the right side of the expression. We don’t have to declare the type of local variables.

public String myMethod(int n){
	var counter = 10;
	var idToNameMap = new HashMap<Integer, String>();
	//some code 
    idToNameMap.foreach(e -> {/*some code*/});
	//some code
    var message = "Hello World";
    message = message.toUpperCase();
    return message;
}

As mentioned before, this is the biggest feature of Java 10,

  • var only works for local variables into a method. Field members, method parameters, return types can’t be var.
  • var won’t work if you don’t initialize the local variable or initialize it with null.
public class Test {
  public var user;  //Wont work, var scope is local 
  
  public void myMethod(var myParam){//Wont work, conflicts with overloaded methods
    var n; // Wont work, not able to infer the type
    var t = null //Wont work, not able to infer the type
  }
}

Java 11

Java 11 is the latest LTS (Long term release) since Java 8. Comparing this version brings to the short term releases it brings more ‘coding’ new features.

– Running Java File with a single command

A very util functionality for people that are starting to learn Java. If we want to run your Java code, you don’t need to execute javac in order to compile and generate the class file and then execute java to run the class file. Now, we can create our code in a Java file, and run it directly.

public class MyApplication {
  public static void main(String [] args){
    System.out.println("Hello World!);
  }
}
$ java MyApplication.java
"Hello World!"

## Before and not more required
## javac MyApplication.java 
## java MyApplication.class

– String methods

Some new methods were added to the String class in order to make easier some actions with this object.

  • isBlank(): returns true if the string is empty or only has white spaces. We can forget to do mystring.trim().isEmpty().
  • strip(), stripLeading(), stripTrailing() : Removes white spaces begging and ending of the string. It’s different from trim() because it’s Unicode aware.
  • lines(): Returns a stream of strings. In other words, split the string into a collection string, the new line character "\n” is used to split the string.
  • repeat(int i): Returns a new String that repeats the string as many numbers of times is indicated.
"abc".repeat(3).equals("abcabcabc") //true

– Local Variable support for Lambdas

In Java 10, Local variable was introduced, but we were not able to use this feature in Lambda Expressions. Now, that’s possible.

//Valid
(var s1, var s2) -> s1 + s2

//NOT VALID
(var s1, String y) s1+ y //Explicit type and local var mixing not allowed
var s1 -> s1.toString() //Parenthesis required

– HTTP Client

Java 11 standardizes the Http Client API. The new API supports both HTTP/1.1 and HTTP/2. It is designed to improve the overall performance of sending requests by a client and receiving responses from the server. It also natively supports WebSockets.

HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

HttpRequest request = HttpRequest.newBuilder()
            .GET()
            .uri(URI.create("https://mydomain.com/api/books"))
            .setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header
            .build();

HttpResponse<String> response = httpClient
			.send(request, HttpResponse.BodyHandlers.ofString());

A lot of better than the legacy UrlHttpConnection before this Java version.

– Reading/Writing Strings to and from the Files

Java 11 introduces a couple of methods to simplify working with Files, and reading and writing it content into a String. We can forget getting bytes and transforming those bytes to String.

Path path = Files.writeString(Files.createTempFile("test", ".txt"), "My File Content");
System.out.println(path);
String s = Files.readString(path);
System.out.println(s); //My File Content

References

Share

You may also like...

2 Responses

  1. July 11, 2020

    […] order to organize better all this information, this post will be split into 3 parts: – Part 1 (Java 9 to Java 11)– Part 2 (Java 12 to Java 14)– Part 3 (A comparison between Java 8 code to Java […]

  2. July 27, 2020

    […] order to organize better all this information, this post will be split into 3 parts: – Part 1 (Java 9 to Java 11)– Part 2 (Java 12 to Java 14)– Part 3 (A comparison between Java 8 code to Java […]

Leave a Reply

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