Java 9 is here and at Simtlix we started using it! – First Part

Java 9 at SimTLiX

Java 9 is here and at Simtlix we started using it! – First Part

by Mariano Bonatti


Java 9 has arrived and it has brought a set of new features and improvements that aim to help programmers with their day to day activities. Java 8 release presented lambda expressions as one of its main features, and Java 9 has four features/improvements that stand out from the rest:

  • Java Shell (jshell),
  • Milling Project Coin which refers to small improvements over existing features,
  • the Java Module System and
  • support for HTTP 2 Clients.


At Simtlix, we have been trying out the new features and we would like to share our experience. We divided it in two articles. The first one will be about the jshell and the milling project coin, where you will find details about these features and examples of how to apply them. Let’s begin!


The Java Shell (REPL = Read-Eval-Print Loop)


This is called jshell and provides an interactive tool to evaluate declarations, statements, and expressions that comply with the Java programming language, together with an API that allows other applications to leverage this functionality. The goal of this tool is to allow programmers to explore the new APIs, check simple expressions, evaluate input and outputs. Autocomplete is also available and semicolons are not required to close an expression!

Every programmer had the necessity to validate an expression, in my case, I can never remember how the substring method works so, I had to create a project and a class and then, compile and run it. Jshell is a very useful tool programmers can use to easily check some expressions or methods we need to implement in our daily routines with no more effort than accessing the terminal and running a command. We should think of it as an assistant tool that can help us in our regular tasks instead of a feature to include in our code. However, if you are looking for a tool that can evaluate graphical interfaces and has debugger support, sorry but jshell won’t help you with that.  The Jshell tool is not intended to be a full-fledged IDE.

Write your first “Hello Word”

In order to access to the jshell just insert the command jshell in cmd console.

Figure1. As you can see in this picture, jshell keeps the value of a variable defined in a previous command, in this case we declared a variable followed by a print of its value.

Defining java methods

Users are also able to define methods and run them with the following command. If the user starts typing the method and presses the “Intro” key, the prompt will change to “…>” to allow the user to keep coding the method.

Figure 2. In this feature a calculateSum(…) method is defined and executed in the next line.

Defining java classes

Programmers can take similar steps to define a class and run the code written.

Also, there are commands to handle the code in the snippet. List, drop, history and help are other available commands.

Figure 3. List, drop, history, help commands.

Other commands

The last command we are going to present here is autocomplete. With this functionality, users can begin typing a sentence (reserved words, method calls, etc) and get suggestions by pressing “Tab”.

Figure 4. Autocomplete.

Jshell provides a lot of possibilities. In order to quit, just type /exit.


Milling Project Coin


The small language changes included in Project Coin as part of JDK 7 have proven easy to use and have worked well in practice. However, a few improvements have been made in Java 9.

In the Java project that accompanies this article, we applied these features in the package com.simtlix.java9.experience.mpc. Feel free to modify it as you see fit in order to understand and explore the different features

1. Underscore as an Identifier Name: Before Java 9, it was possible to use a single underscore to name an identifier. Although there does not seem to be anything wrong with this practice, using it may make our code really hard to read and maintain. Starting from Java 9 this variable name will cause a compiler error. But, what is the real reason for this change? It seems that Java 10 will implement new features in Lambda expression and the language may reserve this name as a keyword and/or give it special semantics. So, do not use underscores as names anymore… because naming a placeholder as underscore is really ugly!

//private String _="hello";
private String _stream = "allowed";
{
    System.out.println(_stream);
}

2. Improvement of try-with-resources Statements: Java 7 introduced the try-with-resources statement. It is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. In Java 7, the resource must be a fresh variable declared in the try block. Java 9 can manage the resource without a new variable being declared if the resource is referenced by a final or effectively final variable.
The previous snipped code shows a try-with-resources in which the resource does not need to be a fresh variable but it uses a variable declared previously.

InputStream inputStream = new FileInputStream( new File("text.txt"));
try (inputStream) {
    System.out.println("Total file size to read (in bytes) : "
                  + inputStream.available());
    int content;
    while ((content = inputStream.read()) != -1) {
        System.out.print((char) content);
    }
} catch (IOException e) {
    System.out.println("Error reading file.");
    e.printStackTrace();
}

3. Private methods in Interfaces: Java 8 provides flexibility to allow Interface to define an implementation which will be used as default in the situation where a concrete Class fails to provide an implementation for that method. This feature was really important because it allows extending Interfaces in a backwards-compatible way.In Java 9, there is an improvement over this feature which allows programmers to define private and private static methods in order to avoid redundant code and add more reusability. These private methods are like any other private method declared in a regular class.
The previous code declares a private method inside an interface. This method is not inherited by the classes that implement this interface, it is just callable from default methods inside the interface.

public interface Animal {
    void eat();
 
    void sleep();
 
    default void makeSound() {
        printString("Default sound!");
    }
 
    private void printString(String value) {
        System.out.println(value);
    }
}

4. SafeVarargs to Support Private Methods: Java 7 introduced the @SafeVarargs annotation type to indicate to the compiler that the body of annotated final or static methods, or constructors do not perform potentially unsafe operations on their varargs. Java 9 expands this capability to also include private methods, as you can see in the below snipped code:

/**
* This method shows the utility of the @SafeVarargs. Try removing this
* annotation and check that the compiler will warn you.
* @param ls
*/
@SafeVarargs
private static void checkSafeVarargsMethod(List... ls) {
    for (List los: ls) {
        System.out.println(los);
    }
}

5. Diamond Operators with Anonymous Classes: Java 7 introduced the diamond operator (<>) in generic class instantiation contexts as below:

List<String> list = new ArrayList<String>();

This piece of code declares a list that only accept String objects in it. Java 9 allow declaring generics inside the anonymous classes as you can see in the below snipped code:

Iterator iter = new Iterator<>() {
    int i = 0;
    @Override
    public boolean hasNext() {
        return i < greetings.length;
    }
 
    @Override
    public String next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return greetings[i++];
    }
};


You will find more details about Java Milling Project Coin in http://openjdk.java.net/jeps/213In this article we gave an overview of two of the most important features included in Java 9. Jshell is good news in order to assist to the developers in their daily tasks. Also, the Milling Project Coin includes some improvements that help the programmer write less code and allows the maintainability and reusability of our code. You will find all code examples used in this article and more in our github.
If you still want to see more about Java 9, you can read the second part of this article in which we will provide an overview of other interesting features included such as modularity, HTTP 2 Client support, process API support and many more…


This article was written with the collaboration of Guillermo Ojeda, Leonardo Marzo, Heraldo Valenti, Facundo Rossi and Denis Reinoso.