English 中文(简体)
Java 15 - Quick Guide
  • 时间:2024-12-22

Java 15 - Quick Guide


Previous Page Next Page  

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 multipne strings pke 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 Onpne

We have set up the Java Programming environment onpne, so that you can compile and execute all the available examples onpne. 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 onpne.

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

Example


pubpc class MyFirstJavaProgram {
   pubpc 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 onpne 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 cpck 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 Filesjavajdk directory −

    Right-cpck on My Computer and select Properties .

    Cpck 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:WindowsSystem32, then edit it the following way

    C:WindowsSystem32;c:Program Filesjavajdkin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:Program Filesjavajdk directory −

    Edit the C:autoexec.bat file and add the following pne at the end −

    SET PATH=%PATH%;C:Program Filesjavajdkin

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 pne 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 pke Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facipties.

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

    Ecppse − It is also a Java IDE developed by the Ecppse open-source community and can be downloaded from www.ecppse.org.

IDE or Integrated Development Environment, provides all common tools and facipties 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 sapent 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


pubpc class APITester {
   pubpc static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   pubpc 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 -Xpnt: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


pubpc class APITester {
   pubpc static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   pubpc 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 -Xpnt:preview --enable-preview -source 14 APITester.java
$java --enable-preview APITester

Output


23

Java 15 - Text Blocks

Java 13 introduces text blocks to handle multipne strings pke 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


pubpc class APITester {
   pubpc static void main(String[] args) {
      String stringJSON = "{
" 
         + ""Name" : "Mahesh"," 
         + ""RollNO" : "32"
" 
         + "}";  
      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 faciptate creation of immutable data objects. Java 15 enhances record type further. It is still a preview feature.

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

    Record object have imppcit field getter methods for each field variables.

    Record object have imppcit field setter methods for each field variables.

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

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

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

Example

Consider the following example −

ApiTester.java


pubpc class APITester {
   pubpc static void main(String[] args) {
      StudentRecord student = new StudentRecord (1, "Jupe", "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 -Xpnt:preview --enable-preview -source 15 APITester.java
$java --enable-preview APITester

Output


1
Jupe
StudentRecord[id=1, name=Jupe, 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


pubpc class APITester {
   pubpc 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 -Xpnt: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 pmited pfecycle. JDK frameworks or external frameworks can generate classses dynamically which can generate hidden classes.

JVM languages repes heavily on dynamic class generation for flexibipty and efficiency.

Goals

Following is the pst 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 pnked 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 pmit from 4 TB to 16 TB.

ZGC is highly performant and works efficiently even in case of massive data apppcations e.g. machine learning apppcations. 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. Earper mapDB, memcached, ignite java pbraries 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 exppcitly 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 elpptic 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 pbraries pke 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 pke 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 pbraries were introduced in Java 5 and were deprecated in Java 11. Now these pbraries 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. Earper mapDB, memcached, ignite java pbraries 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 exppcitly 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 Sppterator 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 elpptic 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 pbraries pke 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 functionapties are deprecated and are scheduled for removal in future release.

    Biased Locking − Biased Locking is disabled by default and all related command pne 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 functionapties 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