Java 23: Module Import Feature

MyExamCloud - Oct 4 - - Dev Community

Java 23 introduces two new preview features: Module Import Declarations (Preview) and Automatic Module Import in Implicitly Declared Classes. These should not be used in production code, as they are still subject to change.

1. Module Import Declarations (Preview) - JEP 476
With the release of Java 23, we are now able to import complete modules in our code. This means that we can import all the classes in the packages exported by that module.

For example, we can import the complete java.base module and use classes like List, Set, Map, and Collectors without having to make individual import statements for each class. This can be done by using the "import module" syntax:



//Old style:
import java.util.Map;                   // or import java.util.*;
import java.util.function.Function;     // or import java.util.function.*;
import java.util.stream.Collectors;     // or import java.util.stream.*;
import java.util.stream.Stream;         // (can be removed)


Enter fullscreen mode Exit fullscreen mode


//New Style:
import module java.base;

public class MyExamCloud {

  public static Map<Character, List<String>> groupByFirstLetter(String...values) {
    return Stream.of(values).collect(
      Collectors.groupingBy(s -> Character.toUpperCase(s.charAt(0))));
  }

}


Enter fullscreen mode Exit fullscreen mode

Note that the importing class does not need to be in a module to use this syntax.

Ambiguous class names may arise if there are two imported classes with the same name. To resolve this, we need to specify the desired class directly in an import statement.

Additionally, when one module transitively imports another module, we can use all the classes in the exported packages of the transitively imported module without any explicit imports. For example, the java.sql module transitively imports the java.xml module, so we can use classes from java.xml without needing to import them explicitly.

2. Automatic Module Import in Implicitly Declared Classes
In Java 23, implicitly declared classes will automatically import the complete java.base module.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player