×
Community Blog Going Beyond Java 8: A Developer's Perspective

Going Beyond Java 8: A Developer's Perspective

This article describes the features in Java versions later than 8 from a developer's perspective, emphasizing how developers can use them to improve performance.

By Chen Libing (Leijuan), a Senior Technical Expert of Alibaba Group, GitHub

Python, JavaScript, and other programming languages are becoming increasingly popular. However, the previously dominant language, Java, despite having lost some favoritism, still retains the top spot in different rankings of major programming languages. It remains the No. 1 language of application development for mainstream enterprise applications. Since the launch of Java 8, Java has introduced many useful new language features and tools that help improve performance. Yet, many programmers have not upgraded to versions later than Java 8 for development. This article describes Java language features in versions later than 8 from the developer's perspective.

First, Java 8 is undoubtedly a milestone version in the eyes of most Java programmers. Its most well-known features are Streams and Lambda expressions, which make functional programming possible and revitalizes Java. This is the very reason that, despite Oracle stopping updates, many Cloud vendors still give great support to Java 8 to stay active for a long time.

Install Alibaba Cloud SDK for Java >>

Many programmers have not upgraded to versions later than Java 8 for development, which is why we are addressing the language features in later versions. This article focuses on the development and skips garbage collection (GC), compiler, Java module, and platform. These topics can be covered in other articles. The following features play a role in code writing.

Java 13 will be released soon, Java versions from Java 9 to Java 13 are all covered. Java releases are adjusted, so that the preview is introduced for a version, followed by reinforcements and improvements based on user feedback. In this article, we don't specifically point out which version has which features. You can just consider them to be a mixture of features for all versions later than Java 8. The reference source for this article is the detailed introduction of each Java version from the Features and Pluralsight sections on the official Java Website.

Var - Local Variable Type Inference

Java supports generics, but if the type is long and you do not care much about it, then use var keywords. This greatly simplifies your code. Java IDE works perfectly with var, so you will not be dealing with frequent code hinting.


Map<String, List<Map<String,Object>>>  store = new ConcurrentHashMap<String, List<Map<String,Object>>>();
        Map<String, List<Map<String,Object>>>  store = new ConcurrentHashMap<>();
        Map<String, List<Map<String,Object>>>  store = new ConcurrentHashMap<String, List<Map<String,Object>>>();
  //lambda
  BiFunction<String, String, String> function1 = (var s1, var s2) -> s1 + s2;
        System.out.println(function1.apply(text1, text2));

Copy the confd file to the bin directory and start confd.

sudo cp bin/confd /usr/local/bin
confd

In practice, you can expect some minor restrictions, such as assigning values to null values. But these are not big issues, so you can get started now.

Process Handle

We only call system commands in Java occasionally. Of course, we mostly use ProcessBuilder to do so. Another feature is the reinforced ProcessHandle, which gives updates of other processes. ProcessHandle helps get all processes, the starting command and start time of a specific process and more.

ProcessHandle ph =  ProcessHandle.of(89810).get();
System.out.println(ph.info());

Collection Factory Methods

Are you still using new methods to create ArrayList and HashSet? You may be behind the curve. Use factory methods directly.

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

New APIs of String Class

It is impossible to list out all the new APIs here, but a good command of several important ones is enough for you to get rid of third-party StringUtils. The following APIs are: repeat, isEmpty, isBlank, strip, lines, indent, transform, trimIndent, formatted.

Supporting HTTP 2

It's easier to use OkHTTP 3, but it is not a problem if you do not want other development packages and prefer to stick with HTTP 2. Java supports HTTP 2, and both synchronous and asynchronous programming models. Also, the code is basically the same.

HttpClient client = HttpClient.newHttpClient();
        HttpRequest req =
                HttpRequest.newBuilder(URI.create("https://httpbin.org/ip"))
                        .header("User-Agent", "Java")
                        .GET()
                        .build();
        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
        System.out.println(resp.body());

Text Block (JDK 13)

In an earlier version, you must type long texts and avoid double quotation marks. The readability is poor. For example:

String jsonText = "{"id": 1, "nick": "leijuan"}";

With the new method of text block:

//language=json
  String cleanJsonText = """
        {"id": 1, "nick": "leijuan"}""";

Much simpler, right? Focus on writing your code, and there is no need to worry about double quotation mark escape, or copy sharing and conversion.

Wait a minute, just what is //language=json that you added in front of cleanJsonText? This is a feature of IntelliJ IDEA. Your text block is semantic. Add //language=json to HTML, JSON, or SQL code, and you immediately get code hinting. Shhh...I can only share this tip with my close friends.

Text block also supports basic template characteristics. Introduce context variables into text block, type %s and call the formatted method. Your job is done.

//language=html
    String textBlock = """
    <span style="color: green">Hello %s</span>""";
    System.out.println(textBlock.formatted(nick));

Improvement of Switch

Arrow Labels

The introduction of the switch arrow "->" eliminates the need to use so many breaks. Here's some sample code.

//legacy
    switch (DayOfWeek.FRIDAY) {
        case MONDAY: {
            System.out.println(1);
            break;
        }
        case WEDNESDAY: {
            System.out.println(2);
            break;
        }
        default: {
            System.out.println("Unknown");
        }
    }
    //Arrow labels
    switch (DayOfWeek.FRIDAY) {
        case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
        case TUESDAY -> System.out.println(7);
        case THURSDAY, SATURDAY -> System.out.println(8);
        case WEDNESDAY -> System.out.println(9);
    }

Switch Expressions

This means that a switch has return values. Here's some sample code.

//Yielding a value
    int i2 = switch (DayOfWeek.FRIDAY) {
        case MONDAY, FRIDAY, SUNDAY -> 6;
        case TUESDAY -> 7;
        case THURSDAY, SATURDAY -> 8;
        case WEDNESDAY -> 9;
        default -> {
            yield 10;
        }
    };

The keyword yield represents the returned value of the switch expression.

Using These Features

All these features seem pretty well, but how can we use them when we are still working with Java 8? What else can we do, except consider these features? Don't worry. Somebody has found a solution.

This item supports transparently compiling all JDK 12+ syntaxes to a Java 8 VM. In other words, it is not a problem to run these syntaxes on Java 8. All these features are available to you, even in the Java 8 environment.

How can they be used? It is all very simple and easy.

First, download the latest JDK, such as JDK 13, and add jabel-java-plugin to the dependency.

<dependency>
            <groupId>com.github.bsideup.jabel</groupId>
            <artifactId>jabel-javac-plugin</artifactId>
            <version>0.2.0</version>
  </dependency>

Then, adjust the compiler plugin of Maven and set the source to the Java version you need, such as Java 13. The target and release can be set to Java 8. IntelliJ IDEA is capable of automatic recognition and does not need adjustment.

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>13</source>
                    <target>8</target>
                    <release>8</release>
                </configuration>
</plugin>

Now, start the pleasant experience of using those features.

Summary

We've discussed some of the most popular and useful features in Java in this blog. Some useful features, such as API adjustment, are not mentioned in this article. However, you can always share them with our community through our blogs or our forum.

0 0 0
Share on

You may also like

Comments