Java 9 Features


Collection factory method for immutable collection.

Java 9 introduced collection factory method to created immutable list, set and map.
Collection set, Map or List have of () method this will create immutable collection.
Earlier to java 9 there was unmodifiable () method in collections to create immutable collection. Refer below code snippet-

public class TestMain {

  public static void main(String[] args) {
      List<Integer> intList = Arrays.asList(1,2,4,5,6,7);
      Collections.unmodifiableCollection(intList);
      intList.forEach(System.out::println);
  }
}

public class Main {
 
public static void main(String args[]){
    List immutableList = List.of(
1,2,3);
    Set immutableSet = Set.of(
1,2,3);
    Map immutableMap = Map.of(
1, "one", 2, "two", 3, "three");
  }
}


private and private static method in interface-

What’s the use of private and private static method in interface as this will not be accessible outside the interface. In Java8 default and default static method were introduced, so these private method are actually helper method of default and default static method refer below code snippet.

public interface Java9Interface {

      default void defaultMethod(){
            privateMethod();
    }
   
    static void defaultStaticMethod(){
      privateStaticMethod();
    }
   
    private void privateMethod(){
        System.out.println("private method..");
    }
   
    private static void privateStaticMethod(){
       System.out.println("private static method..");
    }

}


Improvement in try with resource block-

Try with resource block was introduced in Java 7 but there was a constraint that auto closeable resource must declare inside the try block, This restriction is removed in JAVA 9, refer below code snippet.

class Resource implements AutoCloseable {
      public void close() throws Exception {
            System.out.println("closing..");
      }
}

public class TestMain {

      public static void main(String[] args) {
            try(Resource resource = new Resource()){
                  System.out.println("Resource declare in try block");
            } catch (Exception e) {
                  System.out.println(e.getLocalizedMessage());
            }
           
            //Java 9
            Resource resource = new Resource();
            try(resource){
                  System.out.println("Resource declare outside try block");
            } catch (Exception e) {
                  System.out.println(e.getLocalizedMessage());
            }
      }
}


New methods in stream API-

To enhance an provide more control on functional programming two new methods are introduced in stream API, takeWhile() and dropWhile(), these method accepts the predicate as parameter and check if condition meets its terminate at that point.
This means takeWhile() will accept the value till condition meets that terminate while dropWhile() methods drops all the values till condition meets then accept remaining all value after condition.
Refer below code snippet –
public class TestMain {

  public static void main(String[] args) {
      List<Integer> intList = Arrays.asList(1, 2, 3, 4, 7, 0, 5, 11, 12);

      intList.stream().takeWhile(e -> e < 4).forEach(System.out::println);
      // print 1,2 ,3

      intList.stream().dropWhile(e -> e < 4).forEach(System.out::println);
      // print 4, 7, 0, 5, 11, 12
  }
}


Make looping more function improved IntStream-

Again this an enhancement to provide control on function programming. IntStream can iterate in more advance way by predicate and function as parameter.
Refer below code snippet-
public class TestMain {

  public static void main(String[] args) {
      //imperative style code older version
      for(int count = 0 ;  count < 10 ; count++) {
            System.out.println(count);
      }
      // java 9, more function style code
      IntStream.iterate(0, e-> e < 10, e->e+1).forEach(System.out::println);
      }
}


Improvement in Optional-

To avoid nullpointer exception new methods are added here if value is not present than using isPresentOrElse(), or() method default value can be provided.
Refer below code snippet-
public class TestMain {

      public static void main(String[] args) {
            List<Integer> intList = Arrays.asList(11, 12, 34, 56, 76, 98);

            //method or() accept a supplier for default value.
            Optional<Integer> optional1 = intList.stream().filter(e -> e > 50).findFirst().or(() -> Optional.of(50));
            System.out.println(optional1); //
           
            //method ifPresentOrElse() accept a action if value present and a supplier for default value.
            intList.stream().filter(e -> e > 50).findFirst().ifPresentOrElse(System.out::println, () -> Optional.of(50));
      }
}


Improvement in CompletableFuture-

In JAVA 9, to control the execution on completablefuture on time we can abrupt the future on a given time interval and returns a default value.
Refer below code snippet-
public class TestMain {

      public static void main(String[] args) {
            CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> System.nanoTime());
            future.thenAccept(System.out::println);
            // if completable future doesn't execute on 2 second than it will terminate with
            // default value 2
            future.completeOnTimeout((long) -1, 2, TimeUnit.SECONDS);
           
            CompletableFuture.supplyAsync(() -> System.nanoTime()).orTimeout(1, TimeUnit.MINUTES).thenAccept(System.out::println);
      }
}


Moduler programming

Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications, In Java9 moduler programming were introduced.
JDK itself has divided into set of modules to make it more lightweight. It also allows us to develop modular applications.
To enable modular programming create module-info.java on parallel to base folder
In below code snippet require is used to import modules and exports is used to export the packages.
module mk.study.journal{
      requires jdk.jshell;
exports com.mk.study.journal;
}
Note – by default all module use requires java.base, that needs not to be declare explicitly.


Reactive programming
JAVA 9 added reactive stream API, this API contains publish/subscribe Framework to implement Asynchronous, Scalable and Parallel applications very easily
Java SE 9 has introduced the following API to develop Reactive Streams java.util.concurrent.Flow
java.util.concurrent.Flow.Publisher
java.util.concurrent.Flow.Subscriber
java.util.concurrent.Flow.Processor


JSHELL (REPL) –

Jshell is added for REPL(Read evaluate print loop), there is no need to write complete class and method, in Jshell simply one liner code can execute directly.
Refer below screen shot-

Jshell is used for learning and R&R purpose. Also in Jshell we need not to care of semicolon, or compile time exception handling etc.

2 comments: