Java version 8 and later features

This article describes the features of ** Java ** version 8 and above from a developer's perspective and describes how developers can use them to improve performance.

From Alibaba Group Senior Technical Expert, Leijuan

Programming languages such as Python and JavaScript are becoming more and more popular. However, Java, a former dominant language, remains at the top of various rankings of major programming languages, despite losing some favor. Java remains the number one language for application development for mainstream enterprise applications. Since the launch of Java 8, Java has introduced many useful new language features and tools to help improve performance. However, many programmers have not upgraded to Java 8 or a later version for development. From a developer's perspective, this article describes Java language features in Java 8 and later versions.

First of all, Java 8 is arguably a breakthrough version in the eyes of most Java programmers. Its most famous features are streams and lambda expressions, which enable functional programming and activate Java. That's exactly why many cloud vendors have provided great support for Java 8 and have been active for so long, even though Oracle has stopped updating.

Installing Alibaba Cloud SDK for Java

Many programmers haven't upgraded to a later version than Java 8 for development, so we're covering the language features of later versions. This article focuses on development and skips garbage collection (GC), compilers, Java modules, and platforms. These topics can be covered in other articles. The following features play a role in writing code:

With Java 13 coming soon, all Java versions from Java 9 to Java 13 are covered. Java releases have been tuned, previews have been introduced depending on the version, and then enhancements and improvements will be made based on user feedback. This article does not specifically point out which version has which feature. However, you can think of it as a mixture of features from all versions of Java 8 and above. The source of this article is a detailed introduction to each Java version in the "Features and Pluralsight" section of the official Java website.

Var --Local variable type inference

Java supports generics, but if the type doesn't really care about length, use the var keyword. This greatly simplifies your code. The Java IDE works perfectly with var, so you don't have to deal with code hints often.


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 small restrictions, such as assigning a value to a null value. But these aren't big issues, so you can get started right away.

Process handle

Invoking system commands in Java is rare. Of course, most of the time you use Process Builder for that. Another feature is the enhancement of Process Handle that can get the update information of other processes. ProcessHandle is useful for getting the start command and start time of all processes, a specific process, and so on.

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

Collection factory method

Haven't you created an ArrayList or HashSet using the new method yet? You may be late. Let's use the factory method directly.

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

New API for string classes

It's not possible to list all the new APIs here, but with some important APIs you can get rid of the third-party StringUtils. The following APIs are repeat, isEmpty, isBlank, strip, line, indent, transform, trimIndent, formatted.

Supports HTTP 2

It's easier to use OkHTTP 3, but if you don't want other development packages and want to stick with HTTP 2, that's fine. Java supports HTTP 2 and supports 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)

Earlier versions require you to enter long sentences and avoid double quotes. Readability is reduced. For example:

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

New method of text block:

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

It's much simpler, isn't it? You don't have to worry about escaping double quotes or sharing and converting copies, focusing on writing code.

Wait a minute, what is the // language = json added before cleanJsonText? This is a feature of IntelliJ IDEA and the text blocks are semantic. Add // language = json to your HTML, JSON, or SQL code and you'll immediately get a code hint.

Text blocks also correspond to basic template characteristics. Introduce a context variable into the text block and enter% s to call the formatted method. This completes your work.

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

Switch improvements

Arrow Labels

With the introduction of the switch arrow "→", it is no longer necessary to make so many line breaks. The sample code is introduced below.

//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 formula

This means that the switch has a return value. The sample code is shown below.

//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 return value of a switch expression.

Use of these features

All of these features look good, but how can I use them when I'm still working in Java 8? What else can we do besides considering these features? please do not worry. I found a solution.

This item supports compiling all JDK 12+ syntax transparently into a Java 8 VM. In other words, running these syntaxes on Java 8 is not a problem. All of these features are also available in the Java 8 environment.

So how can it be used? It's all very simple and easy.

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

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

Then tune Maven's compiler plugin and set the source to the required Java version, such as Java 13. Targets and releases can be set to Java 8. IntelliJ IDEA is capable of automatic recognition and does not require 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>

Let's start a comfortable experience with those features.

Overview

This blog has covered some of the most popular and useful features in Java. Some useful features, such as API tweaking, are not mentioned in this article. But you can always share it with our community through blogs and forums.

Recommended Posts

Java version 8 and later features
Java features
Java features
Java 9 new features and sample code
[Java] About Java 12 features
Java version check
About Java features
java1.8 new features
Java and JavaScript
Download and install Eclipse (Java) (Mac version)
XXE and Java
Review notes for Java 1.7 and later file copies
Predicted Features of Java
[Java] Convert PDF version
Getters and setters (Java)
[Java] Thread and Runnable
Java true and false
Java version notation comparison
[Java] String comparison and && and ||
Switching java version (memorial)
Java --Serialization and Deserialization
[Java] Arguments and parameters
timedatectl and Java TimeZone
[Java] Branch and repeat
[Java] Variables and types
[Java] Three features of Java
java (classes and instances)
[Java] Overload and override
Study Java # 2 (\ mark and operator)
Learning Java framework # 1 (Mac version)
Java version control on macOS
How to lower java version
[Java] Difference between == and equals
[Java] Stack area and static area
[Java] Generics classes and generics methods
Java programming (variables and data)
Java encryption and decryption PDF
New features from Java7 to Java8
Java and Iterator Part 1 External Iterator
Micronaut CLI Profiles and Features
Version control Java with SDKMAN
Java if and switch statements
Java class definition and instantiation
Apache Hadoop and Java 9 (Part 1)
[Java] About String and StringBuilder
[Java] HashCode and equals overrides
Java version control with jenv
☾ Java / Iterative statement and iterative control statement
Java methods and method overloads
Java version change on CentOS
java Generics T and? Difference
Advantages and disadvantages of Java
Simplify java version switching (Mac)
java (conditional branching and repetition)
About Java Packages and imports
[Java] Upload images and base64
C # and Java Overrides Story
Java abstract methods and classes
Java while and for statements
Java encapsulation and getters and setters
Look through Java and MySQL PATH with environment variables [Windows version]