Java 9 features with examples

Category : Java | Sub Category : Java 9 introduced features | By Prasad Bonam Last updated: 2023-08-09 07:37:08 Viewed : 323


here are some Java 9 features with examples to illustrate their usage:

  1. Module System (Project Jigsaw):

    Java 9 introduced the module system to improve modularity and encapsulation. Lets create a simple example with two modules, com.example.app and com.example.util:

    java
    // module-info.java in com.example.app module com.example.app { requires com.example.util; } // module-info.java in com.example.util module com.example.util { exports com.example.util; }
  2. JShell (REPL):

    JShell allows you to interactively experiment with Java code:

    java
    // Launch JShell $ jshell // Example usage jshell> int x = 10; x ==> 10 jshell> int y = 20; y ==> 20 jshell> int sum = x + y; sum ==> 30
  3. Factory Methods for Immutable Collections:

    Java 9 introduced factory methods for creating immutable collections:

    java
    // Creating an immutable list List<String> names = List.of("Alice", "Bob", "Charlie"); // Creating an immutable set Set<Integer> numbers = Set.of(1, 2, 3); // Creating an immutable map Map<String, Integer> scores = Map.of("Alice", 100, "Bob", 90);
  4. Private Interface Methods:

    Java 9 allows private methods in interfaces:

    java
    interface MyInterface { default void publicMethod() { privateMethod(); } private void privateMethod() { System.out.println("Private method"); } }
  5. Stream API Enhancements:

    Java 9 added new methods to the Stream API:

    java
    List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); // takeWhile: takes elements while the condition is true List<Integer> evenNumbers = numbers.stream() .takeWhile(n -> n % 2 == 0) .collect(Collectors.toList()); // dropWhile: drops elements while the condition is true List<Integer> afterThree = numbers.stream() .dropWhile(n -> n <= 3) .collect(Collectors.toList());
  6. HTTP/2 Client:

    Java 9 introduced a new HTTP/2 client API:

    java
    import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class HttpExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://www.example.com")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } }

These examples provide a glimpse of the Java 9 features and how they can be used. Remember that you may need a Java 9 runtime environment to execute these examples.

Search
Related Articles

Leave a Comment: