Tuesday, May 28, 2024

Java 17 Features

Category 1: Nice Developer

1.1 Pattern Matching For Switch Statements

1.2 Sealed Classes & Interfaces - Sealed classes and interfaces offer a restriction whether classes/interfaces can extend/implement other classes/interfaces or not.

In simple words, Sealed Classes work by specifying which classes or interfaces are allowed to extend or implement a particular class or interface. This is achieved by using the “sealed” modifier on the parent class or interface, and then specifying the allowed subclasses or implementing classes using the “permits” keyword.

Category 2: Specific Developer 

2.1 Restore Always-Strict Floating-Point Semantics:

It makes floating-point operations consistently strict.

2.2 Enhanced pseudo-Random Number Generators:

It provides a new interface type and implementations for pseudorandom number generators to make it easier to use various PRNG algorithms and to better support stream-based operations.

2.3 Strongly Encapsulated JDK Internals:

It strongly encapsulates all non-critical internal elements of the JDK 

2.4 Foreign Functions & memory API(Incubator):

It introduces an API by which java programs can interpret code and data outside of the java runtime.

 

Category 3: Keeping up with Apple kinds of stuff

3.1 New macOS Rendering pipelines:

It changed the java 2D macOS rendering pipeline for macOS to use Apple Metal API instead of deprecated Apple OpenGL API. 

3.2 macOS/AArch64 Port

 

Category 4: Cleaning up kinds of stuff

4.1 Deprecate the Applet API for Removal:

Applet API will be removed as it was deprecated since JDK9 most browsers do not support it anymore.

4.2 Removal RMI Activation:

Although RMI is still used, the RMI activation mechanism is obsolete with the web technology of the last decade.

4.3 Removal Experimental AOT and JIT Compiler:

Remove the experimental java-based ahead-of-time(AOT) and just-in-time(JIT) compiler.

4.4 Deprecate the Security manager for Removal:

Deprecate the Security Manager for removal in a future release. The Security Manager dates from java 1.0. It has not been the primary means of securing client-side java code for so many years.


Pattern Matching For Switch Statements

Java 17 introduced a new feature called “Pattern Matching for switch Statements” that allows developers to simplify the code for switch statements that involve pattern matching. This feature provides a short and more readable syntax to handle multiple conditions in switch statements.

Before the introduction of this feature, switch statements could only compare the value of a single variable against a series of constants or expressions. Moreover, the previous version of switch statement was limited to byte, short, char, int, Byte, Character, Short, Integer, String, and Enum types. The new feature allows developers to use patterns to match against the value of an object of any type.

Before getting into enhanced switch statements in Java 17 features, let’s get into some background of it.

Note: case statements can now be written as `case …expression ->’ instead of  ‘case expression:’ since Java 12.

Traditional Switch Statement

Here is an example of a traditional switch statement without pattern matching:

public static String getDayOfWeek(int dayNum) {

    String day;

    switch (dayNum) {

        case 1:

            day = "Monday";

            break;

        case 2:

            day = "Tuesday";

            break;

        case 3:

            day = "Wednesday";

            break;

        case 4:

            day = "Thursday";

            break;

        case 5:

            day = "Friday";

            break;

        case 6:

            day = "Saturday";

            break;

        case 7:

            day = "Sunday";

            break;

        default:

            day = "Invalid day";

    }

    return day;

}

Switch Statements Since Java 12

Since the new Java 12 features, the same code can be simplified as follows:

public static String getDayOfWeek(int dayNum) {

    return switch (dayNum) {

        case 1 -> "Monday";

        case 2 -> "Tuesday";

        case 3 -> "Wednesday";

        case 4 -> "Thursday";

        case 5 -> "Friday";

        case 6 -> "Saturday";

        case 7 -> "Sunday";

        default -> "Invalid day";

    };

}

As shown in the example, since Java 12, the case statements now use the new arrow operator (->) to specify the pattern and the result expression. It also eliminates the break statement at each case.

Switch Statements Since Java 17

In addition to using constant patterns, the new feature of java 17 also allows developers to use variable patterns and type patterns. A variable pattern allows you to match against a specific value and assign it to a variable. A type pattern allows you to match against the type of a value.

Here is an example that demonstrates the use of variable and type patterns:

public static int getLength(Object obj) {

    return switch (obj) {

        case String s -> s.length(); // variable pattern

        case List list && !list.isEmpty() -> list.size(); // type pattern

        case null -> 0;

        default -> -1;

    };

}

In the example, the switch expression matches against the object passed as an argument. The first case statement uses a variable pattern to match against a string and assign it to a variable ‘s’, which is then used to return the length of the string. The second case statement uses a type pattern to match against a non-empty list and returns its size. The last case statement matches against null and returns 0. Note that we can also take a null case now. The default case statement returns -1.

Furthermore, this allows you to use expressions as case labels instead of just constants.

Here is an example of how to use the enhanced switch statement with expression labels:

int value = 5;

switch (value) {

    case 1 -> System.out.println("One");

    case 2 -> System.out.println("Two");

    case 3, 4 -> System.out.println("Three or Four");

    case n if n >= 5 && n <= 10 -> System.out.println("Between Five and Ten"); // expression pattern

    default -> System.out.println("Invalid value");

}

In this example, the switch statement checks the value of the value variable. The case statements are written using the enhanced syntax, which allows for expression labels and additional conditions using the if keyword.

Below example shows the summary of types that are allowed in a case label:

public String testType(Object obj) {  

    return switch (obj) {

        case null -> "NULL value";

        case String str -> "It's a String";  

        case Size s -> "Enum Type";

        case Point p -> "Records Type";

        case Employee e -> "Custom Object's Type";

        case int[] ai -> "Array Type";

        case Employee e && e.getName.equals("John") -> "Conditional Statement";  

        default -> "Unknown";

     };

}

 

public enum Size {  

   SMALL, MEDIUM, LARGE;

}

 

public record Point( int i, int j) { ..... }

 

public class Employee{ ..... }

In the example above, record is a new type introduced in Java 14. To know more about records type, kindly go through record type in Java 14 under Java 14 features.

 Pattern Matching for instanceof

Java 17 introduces a short way of pattern matching for the instanceof operator, which helps to simplify the code required for type checks. With pattern matching, you can extract the value of the checked object into a new variable if the check succeeds. This new variable can then be used in following code. It eliminates the need to cast the object into the expected type.

Note that this was a preview feature introduced under Java 14 Features. It has become a permanent feature under the list of Java 17 features.

Here is an example of how pattern matching can simplify code that uses the instanceof operator:

// Old way with pattern matching (Before Java 17)

 

if (obj instanceof String) {

  String str = (String) obj;

  System.out.println(str.length());

}

// New way with pattern matching (Since Java 17)

 

if (obj instanceof String str) {

System.out.println(str.length());

}

In the old way, you need to cast the object to the String type before using its methods. In the new way, you can use pattern matching to extract the value of obj as a String and assign it to the str variable.

 

 

No comments:

Post a Comment