Location>code7788 >text

What's New in Java SE 23

Popularity:823 ℃/2024-09-19 11:17:03

What's New in Java SE 23

Author:Grey

Original address:

Blogspot: Java SE 23 New Features

CSDN: Java SE 23 New Features

source code (computing)

Source repository.Github:java_new_features

Primitive Types in Patterns, instanceof, and switch (preview function)

With instanceof and switch, we can check if an object is of a specific type, and if so, bind the object to a variable of that type, execute a specific program path, and use the new variable in that program path.

public class PrimitiveTypesTest {
    void main() {
        test1("hello world");
        test2("hello world");
        test1(56);
        test2(56);
        test1(());
        test2(());
    }

    private static void test1(Object obj) {
        if (obj instanceof String s && () >= 5) {
            (());
        } else if (obj instanceof Integer i) {
            (i * i);
        } else {
            (obj);
        }
    }

    private static void test2(Object obj) {
        switch (obj) {
            case String s when () >= 5 -> (());
            case Integer i -> (i * i);
            case null, default -> (obj);
        }
    }
}

JEP 455 Two changes were introduced in Java 23:

  • All primitive types can be used in switch expressions and statements, including long, float, double, and boolean.

  • Second, we can also use all primitive types in pattern matching, including instanceof and switch.

In both cases, i.e., switching by long, float, double, and boolean types, and pattern matching with primitive variables, switch, as with all new switching features, must cover all possible cases.

private static void test3(int x) {
    switch (x) {
        case 1, 2, 3 -> ("Low");
        case 4, 5, 6 -> ("Medium");
        case 7, 8, 9 -> ("High");
    }
}

Module Import Declarations (Module Import Declarations, Preview Function)

Enhances the Java programming language with the ability to succinctly import all packages exported by a module. This simplifies reuse of module libraries, but does not require that the imported code itself be in the module. This is a preview language feature.

Since Java 1.0. All classes in the package are automatically imported into each .java file. That's why we don't need an import statement to use theObjectStringIntegerExceptionThread And so on and so forth for a number of reasons.

We can also import complete packages. For example, importing.* means that we don't have to import a separateListSetMapArrayListHashSet cap (a poem)HashMap etc. classes.

JEP 467It now allows us to import the complete module, or more precisely, all the classes in the package from which the module was exported.

For example, we could import the full module, and then use the classes in that module (e.g.ListMapCollectorsStream) without further import:

package .jdk23;

import module ;

public class ModuleImportDeclarationsTest {
    void main() {
        (groupByFirstLetter("a", "abc", "bcd", "ddd", "dddc", "dfc", "bc"));
    }

    public static Map<Character, List<String>> groupByFirstLetter(String... values) {
        return (values).collect((s -> ((0))));
    }
}

If there are two imported classes with the same name, such as Date in the following example, the compiler will get an error:

import module ;
import module ;

If an import module temporarily imports another module, then we can also use the temporary import module to export all the classes in the package without explicitly importing them.

For example, the module escape imports the module:

module  {
  . . .
  requires transitive ;
  . . .
}

Therefore, in the following example, we do not need to explicitly import SAXParserFactory and SAXParser, nor do we need to explicitly import the module:

SAXParserFactory factory = ();
SAXParser saxParser = ();

Flexible Constructor Bodies (second preview)

Prior to JDK 23, the constructor of Child1 in the following code could only initialize the b variable of the child class after constructing the parent class via super.

public class FlexibleConstructorBodies {
    void main() {
        new Child1(1, 2);
    }
}


class Parent {
    private final int a;

    public Parent(int a) {
         = a;
        printMe();
    }

    void printMe() {
        ("a = " + a);
    }
}

// JDK 23 beforehand
class Child1 extends Parent {
    private final int b;

    public Child1(int a, int b) {
        super(verifyParamsAndReturnA(a, b));
         = b;
    }

    @Override
    void printMe() {
        ();
        ("b = " + b);
    }

    private static int verifyParamsAndReturnA(int a, int b) {
        if (a < 0 || b < 0) throw new IllegalArgumentException();
        return a;
    }
}

When we execute the

new Child1(1,2);

At the time of this code, we would have expected the return of the

a = 1
b = 2

However, since the parent class calls theprintMe()and this call is called before the initialization of the b variable, so it results in a program execution of

a = 1
b = 0

In the future, before calling the super constructor with super(...) and before using this(...) before calling the super constructor, and before using this(...) before calling the alternative constructor, we can execute any code that does not access the current constructed instance (i.e., does not access its fields)

In addition, we can initialize the fields of the instance being constructed. For more details, seeJEP 482

On JDK 23, the above code can be adjusted to.

class Child2 extends Parent {
    private final int b;

    public Child2(int a, int b) {
        if (a < 0 || b < 0) throw new IllegalArgumentException();  // ⟵ Now allowed!
         = b;                                                // ⟵ Now allowed!
        super(a);
    }

    @Override
    void printMe() {
        ();
        ("b = " + b);
    }
}

where the constructor, the initialization and judgment of both a and b, can be done before the super(...) function is called before the
fulfillment

new Child2(1,2);

Printing results as expected

a = 1
b = 2

Implicitly Declared Classes and Instance Main Methods (Third preview)

First appeared in JDK 21, seeWhat's New in Java SE 21

It turns out that we write a main method that requires

public class UnnamedClassesAndInstanceMainMethodsTest {

    public static void main(String[] args) {
        ("Hello World!");
    }

}

And the name of the Java file needs to be consistent with UnnamedClassesAndInstanceMainMethodsTest. By JDK 23, the above code can be simplified to

void main() {
    ("hello world");
}

Even the public class ... This paragraph doesn't need to be written either.

more

Java SE 7 and later versions of the new features, continuously updated ...

bibliography

Java Language Changes for Java SE 23

JDK 23 Release Notes

JAVA 23 FEATURES(WITH EXAMPLES