Java 13 Features

Java 13, released in September 2019, continues to improve the Java platform with new features and enhancements. While it is a non-LTS (Long-Term Support) release, Java 13 introduces experimental and preview features that pave the way for future improvements. In this guide, we will explore the key features of Java 13 with examples.

1. Experimental and Preview Features

Switch Expressions (Second Preview)

Java 13 reintroduces switch expressions as a preview feature, with improvements from the initial preview in Java 12. Switch expressions allow the switch statement to be used as an expression, providing a more concise and flexible way to handle multiple cases.

Example

public class SwitchExpressionsExample {
    public static void main(String[] args) {
        String day = "MONDAY";

        // Using switch as an expression with yield
        int result = switch (day) {
            case "MONDAY", "FRIDAY", "SUNDAY" -> 6;
            case "TUESDAY" -> 7;
            case "THURSDAY", "SATURDAY" -> 8;
            case "WEDNESDAY" -> {
                int len = day.length();
                yield len; // Using yield to return a value
            }
            default -> throw new IllegalArgumentException("Invalid day: " + day);
        };

        System.out.println("Result: " + result);
    }
}

Output:

Result: 6

Explanation

  • Yield Statement: The yield statement is introduced to return a value from a switch expression block, providing a more explicit way to specify the result.
  • Improved Readability: Switch expressions reduce boilerplate code and improve the readability and maintainability of Java applications.

Text Blocks (Preview)

Text blocks are introduced as a preview feature in Java 13, providing a new way to define multi-line string literals. This feature simplifies the creation of strings that span multiple lines, making them more readable and less error-prone.

Key Points:

  • Multi-line Strings: Easily define strings that span multiple lines.
  • Improved Readability: No need for concatenation or excessive escape sequences.
  • Indentation Management: Handles common leading whitespace automatically.

Example

public class TextBlocksExample {
    public static void main(String[] args) {
        // Using a text block to define a multi-line string
        String json = """
                      {
                          "name": "Java",
                          "version": 13,
                          "features": ["Text Blocks", "Switch Expressions"]
                      }
                      """;

        System.out.println("JSON:\n" + json);
    }
}

Output:

JSON:
{
    "name": "Java",
    "version": 13,
    "features": ["Text Blocks", "Switch Expressions"]
}

Explanation

  • Multi-Line Strings: Text blocks use triple quotes (""") to define multi-line string literals, preserving the formatting and indentation of the source code.
  • Readability: Text blocks improve the readability of multi-line strings by eliminating the need for escape sequences and concatenation.

ZGC: Uncommit Unused Memory (Experimental)

Java 13 enhances the Z Garbage Collector (ZGC) by allowing it to uncommit unused memory and return it to the operating system. This feature reduces the memory footprint of applications using ZGC and improves resource utilization.

2. Performance Improvements

Dynamic CDS Archives

Java 13 introduces dynamic CDS (Class Data Sharing) archives, allowing the JVM to generate CDS archives at runtime. This feature improves the startup time and performance of Java applications by optimizing class loading.

  • CDS Archives: Dynamic CDS archives store class metadata, allowing the JVM to load classes more efficiently and reduce memory usage.
  • Improved Startup Time: By generating CDS archives dynamically, Java 13 improves the startup time of applications, especially those with complex class hierarchies.

Soft Max Heap Size

Java 13 introduces the concept of a soft max heap size, which allows the JVM to adjust the heap size dynamically based on application workload and system resources. This feature improves the performance and scalability of Java applications by optimizing memory usage.

Explanation

  • Heap Management: The soft max heap size provides more flexibility in managing memory, allowing the JVM to adjust the heap size dynamically to meet the application's needs.
  • Performance and Scalability: By optimizing memory usage, the soft max heap size improves the performance and scalability of Java applications, especially those with variable workloads.

3. JDK Class Library Enhancements

ByteBuffer.slice()

Java 13 enhances the ByteBuffer class with a new slice() method, which allows the creation of a new buffer that shares the content with the original buffer. This method provides more flexibility when working with buffers and improves the efficiency of buffer manipulation.

Example

import java.nio.ByteBuffer;

public class ByteBufferSliceExample {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);

        // Populate the buffer with some data
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }

        // Create a slice of the buffer
        buffer.position(2);
        buffer.limit(6);
        ByteBuffer slice = buffer.slice();

        System.out.println("Original Buffer:");
        printBuffer(buffer);

        System.out.println("Sliced Buffer:");
        printBuffer(slice);
    }

    private static void printBuffer(ByteBuffer buffer) {
        buffer.rewind(); // Reset position to 0
        while (buffer.hasRemaining()) {
            System.out.print(buffer.get() + " ");
        }
        System.out.println();
    }
}

Output:

Original Buffer:
0 1 2 3 4 5 6 7 8 9 
Sliced Buffer:
2 3 4 5 

Explanation

  • Slice Method: The slice() method creates a new buffer that shares the content with the original buffer, starting from the current position and extending to the limit.
  • Efficiency: This method improves the efficiency of buffer manipulation by allowing developers to work with specific portions of a buffer without copying data.

New ByteBuffer.get() and put() Methods

Java 13 enhances the ByteBuffer class with new get() and put() methods that accept an index and a destination/source array. These methods improve the flexibility and performance of buffer manipulation.

Example

import java.nio.ByteBuffer;

public class ByteBufferGetPutExample {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);

        // Populate the buffer with some data
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }

        // Create a destination array
        byte[] destination = new byte[5];

        // Use get() with index to copy data to the destination array
        buffer.get(2, destination, 0, 5);

        System.out.println("Destination Array:");
        for (byte b : destination) {
            System.out.print(b + " ");
        }
    }
}

Output:

Destination Array:
2 3 4 5 6 

Explanation

  • Indexed Access: The new get() and put() methods allow indexed access to the buffer, providing more flexibility and control over buffer manipulation.
  • Performance: These methods improve the performance of buffer operations by allowing direct access to specific elements, reducing the need for additional data copying.

FileSystems.newFileSystem()

Java 13 enhances the FileSystems class with a new `newFile

System()method, which allows the creation of file systems from aPathorURI. This method provides more flexibility in working with file systems and improves the usability of the FileSystems` API.

Example

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.util.Collections;

public class FileSystemExample {
    public static void main(String[] args) throws Exception {
        Path zipPath = Files.createTempFile("example", ".zip");

        // Create a new file system from a ZIP file
        try (FileSystem zipFs = FileSystems.newFileSystem(zipPath, Collections.emptyMap())) {
            // Perform file operations within the ZIP file system
            Files.createDirectory(zipFs.getPath("/exampleDir"));
            Path filePath = zipFs.getPath("/exampleDir/example.txt");
            Files.writeString(filePath, "Hello, Java 13!");

            System.out.println("File Content: " + Files.readString(filePath));
        }
    }
}

Output:

File Content: Hello, Java 13!

Explanation

  • New File Systems: The newFileSystem() method allows the creation of new file systems from a Path or URI, enabling more flexible file operations and improving the usability of the FileSystems API.
  • ZIP File Systems: In this example, a new file system is created from a ZIP file, allowing file operations to be performed within the ZIP archive.

4. Other Changes in Java 13

Java 13 includes several other changes that enhance the platform and improve performance.

Reimplement the Legacy Socket API

Java 13 reimplements the legacy socket API to improve its performance, scalability, and maintainability. This change enhances the efficiency and reliability of network communication in Java applications.

  • Performance and Scalability: The reimplementation of the legacy socket API improves the performance and scalability of network operations, making Java applications more efficient and responsive.
  • Maintainability: By updating the legacy socket API, Java 13 ensures the long-term maintainability and compatibility of network communication in Java applications.

Unicode 12.1

Java 13 supports Unicode 12.1, which includes additional characters, scripts, and emoji. This support enhances Java's ability to handle diverse character sets and languages, improving internationalization capabilities.

  • Expanded Character Set: Unicode 12.1 support allows developers to work with a broader range of characters and languages, enabling applications to better serve global audiences.
  • Improved Internationalization: By supporting the latest Unicode standard, Java 13 enhances its ability to handle international text and data, improving the usability and accessibility of applications worldwide.

Conclusion

Java 13 introduces several key features and improvements, including switch expressions, text blocks, and enhancements to the ByteBuffer and FileSystems classes. These features enhance developer productivity, application performance, and the flexibility of the Java platform. By understanding and leveraging these features, developers can build more efficient and maintainable Java applications.

For a complete list of all changes in Java 13, refer to the official Java 13 release notes.

Series: Java Release-wise New Features

Comments