Java 13 - Quick Guide



Java 13 - Overview

Java 13 is a major feature release and it has brought many JVM specific changes to JAVA and few language specific changes. It followed the Java release cadence introduced Java 10 onwards and it was releasd on Sept 2019, just six months after Java 12 release.

Java 13 is a non-LTS release.

New Features

Following are the major new features which are introduced in Java 13.

  • JEP 354 - Switch Expressions - A preview feature allowing switch to use return values via yield.

  • JEP 355 - Text Blocks - A preview feature to handle multiline strings like JSON, XML easily.

  • String new methods - New Methods added to string to handle text blocks.

  • JEP 353 - Socket API Reimplementation - Underlying API is rewritten.

  • FileSystems.newFileSystem() - Three new methods added to make it easy to use.

  • DOM/SAX Factories - New methods added to add namespace support.

  • Dynamic CDS Archive - CDS archive can be created easily.

  • JEP 351 - ZGC Enhancements - ZGC enhanced to return unused heap memory to operating system.

Java 13 enhanced numerous APIs with new methods and options. We'll see these changes in next chapters.

Java 13 - Environment Setup

Local Environment Setup

If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.

Java SE is available for download for free. To download click here, please download a version compatible with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way

    C:\Windows\System32;c:\Program Files\java\jdk\bin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Edit the 'C:\autoexec.bat' file and add the following line at the end −

    SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc

    export PATH=/path/to/java:$PATH'

Popular Java Editors

To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.

  • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/.

IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

Java 13 - Switch Expressions

Java 12 introduces expressions to Switch statement and released it as a preview feature. Java 13 added a new yield construct to return a value from switch statement. It is still a preview feature.

Consider the following example:

ApiTester.java

Example

public class APITester {

   public static void main(String[] args) {
      System.out.println("Old Switch");
      System.out.println(getDayTypeOldStyle("Monday"));
      System.out.println(getDayTypeOldStyle("Saturday"));
      System.out.println(getDayTypeOldStyle(""));

      System.out.println("New Switch");
      System.out.println(getDayType("Monday"));
      System.out.println(getDayType("Saturday"));
      System.out.println(getDayType(""));
   }

   public static String getDayType(String day) {

      var result = switch (day) {
         case "Monday", "Tuesday", "Wednesday","Thursday", "Friday" -> yield "Weekday";
         case "Saturday", "Sunday" -> yield "Weekend";
         default -> "Invalid day.";
      };
      return result;
   }

   public static String getDayTypeOldStyle(String day) {
      String result = null;

      switch (day) {
         case "Monday":
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
         case "Friday":
            result = "Weekday";
            break;
         case "Saturday": 
         case "Sunday":
            result = "Weekend";
            break;
         default:
            result =  "Invalid day.";            
      }

      return result;
   }
}

Compile and Run the program

$javac -Xlint:preview --enable-preview -source 13 APITester.java

$java --enable-preview APITester

Output

Old Switch
Weekday
Weekend
Invalid day.
New Switch
Weekday
Weekend
Invalid day.

Java 13 - Text Blocks

Java 13 introduces text blocks to handle multiline strings like JSON/XML/HTML etc. It is a preview feature.

  • Text Block allows to write multiline strings easily without using \r\n.

  • Text Block string have same methods as string like contains(), indexOf() and length() functions.

Example

Consider the following example:

ApiTester.java

public class APITester {

   public static void main(String[] args) {
      String stringJSON = "{\r\n" 
         + "\"Name\" : \"Mahesh\",\r\n" 
         + "\"RollNO\" : \"32\"\r\n" 
         + "}";  
   
      System.out.println(stringJSON);
	  
	  String textBlockJSON = """
         {
            "name" : "Mahesh",
            "RollNO" : "32"
         }
         """;
      System.out.println(textBlockJSON);
	  
	  System.out.println("Contains: " + textBlockJSON.contains("Mahesh"));
	  System.out.println("indexOf: " + textBlockJSON.indexOf("Mahesh"));
	  System.out.println("Length: " + textBlockJSON.length());
   }   
}

Compile and Run the program

$javac -Xlint:preview --enable-preview -source 13 APITester.java

$java --enable-preview APITester

Output

{
"Name" : "Mahesh",
"RollNO" : "32"
}
{
   "name" : "Mahesh",
   "RollNO" : "32"
}

Contains: true
indexOf: 15
Length: 45

Java 13 - Text Block Methods

Java 12 introduces text blocks to handle multiline strings like JSON/XML/HTML etc and added new methods to String class to handle text blocks. It is a preview feature.

  • stripIndent() - removes incidental white spaces from the start and end of the string.

  • translateEscapes() - translate the escape sequences as per the string syntax.

  • formatted() - similar to String format() method to support formatting in text block strings.

Example

Consider the following example:

ApiTester.java

public class APITester {

   public static void main(String[] args) {
	  String textBlockJSON = """
         {
            "name" : "%s",
            "RollNO" : "%s"
         }
         """.formatted("Mahesh", "32");
      System.out.println(textBlockJSON);
   }   
}

Compile and Run the program

$javac -Xlint:preview --enable-preview -source 13 APITester.java

$java --enable-preview APITester

Output

{
"Name" : "Mahesh",
"RollNO" : "32"
}
{
   "name" : "Mahesh",
   "RollNO" : "32"
}

Contains: true
indexOf: 15
Length: 45

Java 13 - Socket API Reimplementation

Java 13 have reimplemented the Java Socket API. Old Socket APIs like java.net.Socket and java.net.ServerSocket has been replaced.

  • PlainSocketImpl is no more in use, now the Socket API provider points to NioSocketImpl.

  • New implementation leverages the java.nio infrastructure for better concurrency and i/o control.

  • New implementation is backwards compatible with code using older implementation.

  • New implementation is now default with Java 12.

  • Old implementation can be selected by multiple ways:

    • Set system property jdk.net.usePlainSockteImpl to true.

    • Run java with -Djdk.net.usePlainSocketImpl option.

    • Update JDK network configuration file available in ${java.home}/conf/net.properties.

  • Old implementation and system property to select old implementation will be removed from future release.

Java 13 - Miscellaneous Changes

Java 13 have introduced three new methods to java.nio.file.FileSystems to treat the content of a file as a file system easily.

  • newFileSystem(Path)

  • newFileSystem(Path, Map<String, ?>)

  • newFileSystem(Path, Map<String, ?>, ClassLoader)

Following are other major changes added to language.

  • java.time – Japanese era name added

  • javax.crypto – MS Cryptography Next Generation (CNG)support

  • javax.security – jdk.sasl.disabledMechanisms property added disabling SASL mechanisms

  • javax.xml.crypto – String constants introduced to represent Canonical XML 1.1 URIs

  • javax.xml.parsers – Methods added to instantiate DOM and SAX factories for namespaces support

  • Unicode support is upgraded to version 12.1

  • Kerberos principal name canonicalization support added, cross-realm referrals are supported.

API marked for Removal

  • SocketImpl implementations prior to JDK 1.4

  • javax.security.cert API

  • rmic

  • javadoc tool old features

Other details are available at following link.APIs proposed for removal.

Java 13 - Dynamic CDS archive

CDS, Class Data Sharing is an important feature of JVM to boost the startup time of an application loading. As it allows to share class metadata across different JVMs, it reduces the startup time and memory footprint. Java 10 enhanced CDS by giving AppCDS, application CDS which gave developers access to include application classes in a shared archive. Java 12 set CDS archive as default.

But the process of creating a CDS was tedious as developers has to go through multiple trials of their applications to create a class list as first step and then dump that class list into an archive. Then this archive can be used to share metadata between JVMs.

From Java 13 onwards, now java has dynamic archiving. Now developers can generate a shared archive at the time of application exit. So trial runs are no more needed.

Following step showcases to create a dynamic shared archive on top of default system archive using option -XX:ArchiveClassesAtExit and passing the archive name.

$java -XX:ArchiveClassesAtExit=sharedApp.jar -cp APITester.jar APITester

Once generated the shared archive can be used to run the application using -XX:SharedArchiveFile option.

$java -XX:SharedArchiveFile=sharedApp.jar -cp APITester.jar APITester

Example

Consider the following example:

APITester.java

public class APITester {
   public static void main(String[] args) {
      System.out.println("Welcome to TutorialsPoint.");
   }   
}

Compile and Run the program

$javac APITester.java

$jar cf APITester.jar APITester.class

$java -XX:ArchiveClassesAtExit=sharedApp.jsa -cp APITester.jar APITester

$java -XX:SharedArchiveFile=sharedApp.jsa -cp APITester.jar APITester

Output

Welcome to TutorialsPoint.

Java 13 - ZGC Enhancements

The ZGC or Z Garbage Collector was introduced with Java 11 as a low latency garbage collection mechnism. ZGC makes sure that Garbage Collection pause time is not dependent on heap size. It will never exceed 10 ms no matter heap size is 2MB or 2GB.

But ZGC had a limitation on returning unused heap memory to operating system like other HotSpot VM GCs such as G1 and Shenandoah. Following are the enhancements done with Java 13:

  • ZGC returns uncommited memory to operating system by default until the maximum heap size is reached.

  • ZGC gives performance improvement with a reduced memory footprint.

  • ZGC now supports heap size of 16 TB as compared to 4TB size limit.

In order to move back to Java 11 way of Garbage Collection, we can use following options:

  • using -XX:-ZUncommit option

  • set -Xms and -Xmx heap size as same.

Advertisements