Java 15 - Quick Guide



Java 15 - Overview

Java 15 is a major feature release and it has brought many JVM specific changes and language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was released on Sep 2020, just six months after Java 14 release.

Java 15 is a non-LTS release.

New Features

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

  • JEP 360 - Sealed Classes − To provide fine grained control over the inheritance.

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

  • JEP 375 - Pattern matching Type Check − enhancements to existing pattern matching preview feature of Java 14.

  • JEP 371 - Hidden Classes − To allow runtime creation of non-discoverable classes.

  • JEP 384 - Records − A preview feature enhancing a new type record introduced in Java 14.

  • JEP 383 - Foreign Memory Access API − Enhancement to incubating feature of java 14.

  • JEP 377, 379 - Garbage Collectors − ZDC and Shenandoah garbage collectors are now part of standard API.

  • JEP 339 - Edwards-Curve Digital Signature Algorithm (EdDSA) − Cryptographic signatures are now implemented using EdDSA.

  • JEP 373 - Reimplement the Legacy DatagramSocket API − legacy implementations of the java.net.DatagramSocket and java.net.MulticastSocket APIs are replaced with simpler and more modern implementations which are easy to maintain and debug.

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

Java 15 - Environment Setup

Live Demo Option Online

We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

Try the following example using Live Demo option available at the top right corner of the below sample code box −

Example

public class MyFirstJavaProgram {
   public static void main(String []args) {
      System.out.println("Hello World");
   }
}

Output

Hello World

For most of the examples given in this tutorial, you will find a Live Demo option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.

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 www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from 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 15 - Sealed Classes

Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Following are salient points to consider for a sealed class −

  • Sealed class is declared using sealed keyword.

  • Sealed classes allow to declare which class can be a subtype using permits keyword.

  • A class extending sealed class must be declared as either sealed, non-sealed or final.

  • Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.

Example

Consider the following example −

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   public static int getId(Person person) {
      if (person instanceof Employee) {
         return ((Employee) person).getEmployeeId();
      } 
      else if (person instanceof Manager) {
         return ((Manager) person).getManagerId();
      }
      return -1;
   }
}
abstract sealed class Person permits Employee, Manager {
   String name;
   String getName() {
      return name;
   }
}
final class Employee extends Person {
   String name;
   int id;
   Employee(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getEmployeeId() {
      return id;
   }
}
non-sealed class Manager extends Person {
   int id;
   Manager(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getManagerId() {
      return id;
   }
}

Compile and Run the program

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

Output

23

Java 15 - Pattern matching in instanceof

Java 14 introduces instanceof operator to have type test pattern as is a preview feature. Type test pattern has a predicate to specify a type with a single binding variable. It continues to be a preview feature in Java 15 as well.

Syntax

if (person instanceof Employee e) {
   return e.getEmployeeId();
}

Example

Consider the following example −

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   public static int getId(Person person) {
      if (person instanceof Employee e) {
         return e.getEmployeeId();
      } 
      else if (person instanceof Manager m) {
         return m.getManagerId();
      }
      return -1;
   }
}
abstract sealed class Person permits Employee, Manager {
   String name;
   String getName() {
      return name;
   }
}
final class Employee extends Person {
   String name;
   int id;
   Employee(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getEmployeeId() {
      return id;
   }
}
non-sealed class Manager extends Person {
   int id;
   Manager(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getManagerId() {
      return id;
   }
}

Compile and Run the program

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

Output

23

Java 15 - Text Blocks

Java 13 introduces text blocks to handle multiline strings like JSON/XML/HTML etc as is a preview feature. With Java 14, we've second preview of Text Blocks. Now Text Block is no more a preview feature and is a part of standard offering.

Example

Consider the following example −

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      String stringJSON = "{\r\n" 
         + "\"Name\" : \"Mahesh\"," 
         + "\"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 APITester.java
$java APITester

Output

{
   "Name" : "Mahesh","RollNO" : "32"
}
{
   "name" : "Mahesh",   "RollNO" : "32"
}
Contains: true
indexOf: 15
Length: 45

Java 15 - Record

Java 14 introduces a new class type record as preview feature to facilitate creation of immutable data objects. Java 15 enhances record type further. It is still a preview feature.

  • Record object have implicit constructor with all the parameters as field variables.

  • Record object have implicit field getter methods for each field variables.

  • Record object have implicit field setter methods for each field variables.

  • Record object have implicit sensible implementation of hashCode(), equals() and toString() methods.

  • With Java 15, native methods cannot be declared in records.

  • With Java 15, implicit fields of record are not final and modification using reflection will throw IllegalAccessException.

Example

Consider the following example −

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      StudentRecord student = new StudentRecord (1, "Julie", "Red", "VI", 12);
      System.out.println(student.id());
      System.out.println(student.name());
      System.out.println(student);
   }
}
record StudentRecord(int id, 
   String name, 
   String section, 
   String className,
   int age){}

Compile and Run the program

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

Output

1
Julie
StudentRecord[id=1, name=Julie, section=Red, className=VI, age=12]

Java 15 - Record for Sealed Interfaces

As records are final by default and can extend interfaces. We can define sealed interfaces and let record implement them for better code management.

Example

Consider the following example −

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      Person employee = new Employee(23, "Robert");
      System.out.println(employee.id());
	   System.out.println(employee.name());
   }
}
sealed interface Person permits Employee, Manager {
   int id();
   String name();
}
record Employee(int id, String name) implements Person {}
record Manager(int id, String name) implements Person {}

Compile and Run the program

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

Output

23
Robert

Java 15 - Hidden Classes

Java 15 has introduced hidden classes which cannot be used directly by other classes bytecode. These hidden classes are intended to be used by frameworks which genereate classes at runtime and use them using reflection.

A hidden class is defined as a member of Nest Based Access Control Context and it can be unloaded inrespective of other classes.

This proposal, JEP 371, aims at improvement of all languages on JVM by providing a standard API to define hidden classes which are not discoverable and have limited lifecycle. JDK frameworks or external frameworks can generate classses dynamically which can generate hidden classes.

JVM languages relies heavily on dynamic class generation for flexibility and efficiency.

Goals

Following is the list of targetted goals of this enhancement.

  • Frameworks should be able to define classes as non-discoverable implementation details of the framework, These classes cannot neither be linked to other classes nor discoverable using reflection.

  • Extend Access Control Nest with non-discoverable classes.

  • Aggressive unloading of hidden classes which will help frameworks to define as many as hidden classes as required without degrading the performance.

  • Depreate the non-standard API, misc.Unsafe::defineAnonymousClass, to be removed in future release.

Java 15 - Garbage Collectors

Java 15 has made the ZGC, Z Garbage Collector a standard feature. It was an experimental feature till Java 15. It is low latency, highly scalable garbage collector.

ZGC was introduced in Java 11 as an experimental feature as developer community felt it to be too large to be released early. A lot of improvements are done to this garbage collection since then, for example −

  • Concurrent class unloading

  • Uncommiting of unused memory

  • Support for Class Data Sharing

  • NUMA Awareness

  • Multithreaded Heap Pre-touch

  • Max Heap Size limit from 4 TB to 16 TB.

ZGC is highly performant and works efficiently even in case of massive data applications e.g. machine learning applications. It ensures that there is no long pause while processing the data due to garbage collection. It supports Linux, Windows and MacOS.

The Shenandoah low-pause-time garbage collector is now out of the experimental stage. It had been introduced into JDK 12 and from java 15 onwards, it is a part of standard JDK.

Java 15 - Other Changes

JEP 383 - Foreign Memory Access API

Java 14 allowed java programs to safely and efficiently access foreign memory outside of the Java heap. Earlier mapDB, memcached, ignite java libraries provided the foreign memory access. It is a cleaner API to operate on all types of foreign memories(native memory, persistent memory, managed heap memory etc. ) in a seamless way. It also takes care of safety of JVM regardless of foreign memory type. Garbage collection/Memory deallocation operations should be explicitly mentioned as well.

This API is based on three main abstractions MemorySegment, MemoryAddress and MemoryLayout and is a safe way to access both heap as well as non-heap memory.

Java 15 continue this feature as incubating and added new refinements to the API.

JEP 339 − Edwards-Curve Digital Signature Algorithm (EdDSA)

Edwards-Curve Digital Signature Algorithm, EdDSA is an advanced elliptic curve scheme and is better than existing signature schemes in the JDK. It has improved security and performance as compared to other signature schemes. It is supported by popular crypto libraries like OpenSSL, BoringSSL etc. EdDSA will only be implemented in java 15 only in the SunEC provider.

JEP 373 − Reimplement the Legacy DatagramSocket API

Legacy implementations of the java.net.DatagramSocket and java.net.MulticastSocket APIs are replaced with simpler and more modern implementations which are easy to maintain and debug.

The current implementations of java.net.datagram.Socket and java.net.MulticastSocket are in jdk from 1.0, IPv6 was still under development. This JEP targets to replace current implementation of MulticastSocket which has reconciled IPv4 and IPv6 in ways that are difficult to maintain.

Java 14 - Deprecation & Removals

Deprecations

  • Solaris and SPARC Ports (JEP 362) − because this Unix operating system and RISC processor are not in active development since the past few years.

  • ParallelScavenge + SerialOld GC Combination (JEP 366) − since this is a rarely used combination of GC algorithms, and requires significant maintenance effort

Removals

  • Concurrent Mark Sweep (CMS) Garbage Collector (JEP 363) − This GC was deprecated in Java 9 and is replaced with G1 as default GC. There are other high performant alternatives as well like ZDC, Shenandoah. This GC was kept for 2 years for interested users to maintain. As there is no active maintenance, this GC is now completed removed from Java 14.

  • Pack200 Tools and API (JEP 367) − These compression libraries were introduced in Java 5 and were deprecated in Java 11. Now these libraries are completely removed from Java 14.

Java 15 - Other Enhancements

JEP 383 - Foreign Memory Access API

Java 14 allowed java programs to safely and efficiently access foreign memory outside of the Java heap. Earlier mapDB, memcached, ignite java libraries provided the foreign memory access. It is a cleaner API to operate on all types of foreign memories(native memory, persistent memory, managed heap memory etc.) in a seamless way. It also takes care of safety of JVM regardless of foreign memory type. Garbage collection/Memory deallocation operations should be explicitly mentioned as well.

This API is based on three main abstractions MemorySegment, MemoryAddress and MemoryLayout and is a safe way to access both heap as well as non-heap memory.

Java 15 continue this feature as incubating and added new refinements to the API.

  • VarHandle API introduced to customize memory access var handles.

  • Parallel processing of a memory segment is supported using the Spliterator interface.

  • Mapped memory segments support enhanced.

  • Native calls addresses can be manipulated and dereferenced.

JEP 339 − Edwards-Curve Digital Signature Algorithm (EdDSA)

Edwards-Curve Digital Signature Algorithm, EdDSA is an advanced elliptic curve scheme and is better than existing signature schemes in the JDK. It has improved security and performance as compared to other signature schemes. It is supported by popular crypto libraries like OpenSSL, BoringSSL etc. EdDSA will only be implemented in java 15 only in the SunEC provider.

JEP 373 − Reimplement the Legacy DatagramSocket API

Legacy implementations of the java.net.DatagramSocket and java.net.MulticastSocket APIs are replaced with simpler and more modern implementations which are easy to maintain and debug.

The current implementations of java.net.datagram.Socket and java.net.MulticastSocket are in jdk from 1.0, IPv6 was still under development.This JEP targets to replace current implementation of MulticastSocket which has reconciled IPv4 and IPv6 in ways that are difficult to maintain.

Text Blocks as Standard

Text blocks from Java 15 are no more preview. Now they are part of standard JDK.

Helpful NullPointerException

Helpful NullPointerException is now enabled by default in Java 15.

Java 15 - Deprecation & Removals

Deprecation

Following functionalities are deprecated and are scheduled for removal in future release.

  • Biased Locking − Biased Locking is disabled by default and all related command line options are deprecated. JDK community is looking to check the need to difficult to maintain legacy synchronization mechanism of biased locking. Biased locking was used in HotSpot virtual machine to reduce overhead of uncontended locking.

  • RMI Activation − RMI activation is an optional part since Java 8 and is obsolete part of RMI. It was imposing an ongoing maintenance cost.

Removals

Following functionalities are removed.

  • Nashorn JavaScript engine − Nashorn JavaScript engine introduced in Java 8 is now removed. With advent of GraalVM and other VM technologies, Nashorn was no longer used in Java ecosystem.

  • Solaris/SPARC ports − Source Code and support for Solaris/SPARC, Solaris/x64, and Linux/SPARC ports which were deprecated in Java 14 are removed. Solaris and SPARC are superseded by Linux OS and Intel processors. So removing their code will help contributors to focus on development of new features to be added to the platform.

Advertisements