Java 9 Extra Edge

Overview



















Java 9 Features

  • Java platform module system (Jigsaw Project)

  • Interface Private Methods

  • HTTP 2 Client

  • JShell - REPL Tool

  • Platform and JVM Logging

  • Process API Updates

  • Collection API Updates

  • Stream API Improvements

  • Diamond operator for anonymous classes

  • Reactive Programming

  • @Deprecated Tag Changes

  • Miscellaneous Other Features



Java Platform Module System (Jigsaw Project)

Compilation
$javac -d mods \
src/shailesh/module-info.java \
src/shailesh/com/in/blr/Vehicle.java
src/shailesh/module-info.java \
src/shailesh/com/in/blr/Vehicle.java

Compilation with Module Path

$javacmodulepath  mods  –d  mods  \ 
  src/zoop/module-info.java  \ 
  src/zoop/com/azul/zoop/alpha/Name.java 
src/zoop/module-info.java 
src/zoop/com/azul/zoop/alpha/Name.java 
mods/zoop/module-info.class 
mods/zoop/com/azul/zoop/alpha/Name.java

Packaging with Modular JARS
 
mods/zoop/module-info.class 
mods/zoop/com/azul/app/Main.class
 
  app.jar
  module-info.class 
  com/azul/zoop/Main.class 
$  jar  --create  --file  myLib/app.jar  \ 
  --main-class  com.azul.zoop.Main  \ 
  -C  mods.
Application Execution (JAR)
$ java -mp myLib:mods -m com.evolvus.app.main


Interface Private Methods

Java 9 onward, you are allowed to include private methods in interfaces. Using private methods, now encapsulation is possible in interfaces as well.

In Java 7 and all earlier versions, interfaces were very simple. They could only contain public abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface.

*************************************************
Java 7

public interface CustomInterface {
   public abstract void method();
}


public class Java7DefaultTester implements CustomInterface{
 
 
    public void method() {
        System.out.println("Hello World");
    }
 
    public static void main(String[] args){
        CustomInterface instance = new Java7DefaultTester();
        instance.method();
    }
}

***************************************************

Java 8

public interface CustomInterface {
    
    public abstract void method1();
    
    public default void method2() {
        System.out.println("default method");
    }
    
    public static void method3() {
        System.out.println("static method");
    }
}


public class CustomClass implements CustomInterface {
 
    @Override
    public void method1() {
        System.out.println("abstract method");
    }
    
    public static void main(String[] args){
        CustomInterface instance = new CustomClass();
        instance.method1();
        instance.method2();
        CustomInterface.method3();
    }
}

*********************************************************************************

Java 9 

Since java 9, you will be able to add private methods and private static method in interfaces.

It will improve code re-usability inside interface. Using Private method in interface have four rules:
1. Private interface method  
2. Private Method can be used only inside interface
3. Private static method can be used inside other static and non-static interface method
4. Private non-static methods cannot be used inside private static methods.

public interface CustomInterfaceFor9 { 
  public abstract void method1();   
    public default void method2() {
        method4();  //private method inside default method
        method5();  //static method inside other non-static method
        System.out.println("default method");
    }    
    public static void method3() {
        method5(); //static method inside other static method
        System.out.println("static method");
    }    
    private void method4(){
        System.out.println("private method");
    }     
    private static void method5(){
        System.out.println("private static method");
    }
}


public class Java9DefaultTester implements CustomInterfaceFor9{
 
  public void method1() {
        System.out.println("abstract method");
    }
    
    public static void main(String[] args){
      CustomInterfaceFor9 instance = new Java9DefaultTester();
        instance.method1();
        instance.method2();
        CustomInterfaceFor9.method3();
    }
}

*****************************************************************************

HTTP2 Client

HTTP/1.1 client was released on 1997. A lot has changed since. So for Java 9 a new API been introduced that is cleaner and clearer to use and which also adds support for HTTP/2. New API uses 3 major classes i.e. HttpClient, HttpRequest and HttpResponse.

public class Http2ClientExample {
 
  public static void main(String[] args) throws IOException, InterruptedException {
 
  HttpClient client = HttpClient.newHttpClient();
  HttpRequest request = HttpRequest.newBuilder(URI.create("https://www.google.com")).GET().build();
  HttpResponse.BodyHandler responseBodyHandler = HttpResponse.BodyHandler.asString();
  HttpResponse response = client.send(request, responseBodyHandler);
  System.out.println("Status code = " + response.statusCode()); 
  String body = response.body().toString();
  System.out.println(body);
 
  } 
}

Output:
Status code = 302
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="https://www.google.co.in/?gfe_rd=cr&amp;dcr=0&amp;ei=lketWbPeJazy8AfW9KvQBg">here</A>.
</BODY></HTML>

Note :  --add-modules jdk.incubator.httpclient in vm argument to use incubator module for http/2 support.



JShell - REPL Tool

JShell is new command line interactive tool
 shipped with JDK 9 distribution [JEP 222] to evaluate declarations, statements and expressions written in Java
JShell allows us to execute Java code snippets and get immediate results without having to create a solution or project.
JShell is Java specific. It has lots of other capabilities, other than executing simple code snippets. e.g.
§Launch inbuilt code editor in separate window
§Launch code editor of your choice in separate window
§Execute code when Save operation happen in these external editors
§Load pre-written classes from file system


Process API Updates

Prior to Java 5, the only way to spawn a new process was to use the Runtime.getRuntime().exec() method. Then in Java 5, ProcessBuilder API was introduced which supported a cleaner way of spawning new processes.
Now Java 9 is adding a new way of getting information about current and any spawned process.
To get information of any process, now you should use java.lang.ProcessHandle.Info interface.
This interface can be useful in getting lots of information e.g.
The command used to start the process
The arguments of the command
Time instant when the process was started
Total time spent by it and the user who created it

public class ProcessDemo {
  public static void main(String[] args) throws IOException
     {

  ProcessHandle.allProcesses().filter(ph -> ph.info().command().isPresent()).forEach(p ->
  System.out.println(p.pid() + " " + p.info().commandLine()));
      
       
     }
}

Output:
1614 Optional[/lib/systemd/systemd --user]
1624 Optional[/sbin/upstart --user]
1701 Optional[/sbin/upstart-udev-bridge --daemon --user]
1715 Optional[/usr/bin/dbus-daemon --fork --session --address=unix:abstract=/tmp/dbus-bl2Xpdw97Y]
1727 Optional[/usr/lib/x86_64-linux-gnu/hud/window-stack-bridge ]
1752 Optional[/sbin/upstart-dbus-bridge --daemon --session --user --bus-name session]
--------------------------------------


Collection API Updates

Since Java 9, you can create immutable collections such as immutable list, immutable set and immutable map using new factory methods. e.g.

public class ImmutableCollections
  public static void main(String[] args) { 
//Immutable List 
List<String> listNames = List.of("Shailesh", "Bangalore",
"USA", "Dubai");
System.out.println("List-->"+listNames); 
 
//Immutable Set 
Set<String> setNames = Set.of("Shailesh", "Bangalore",
"USA","Dubai");
System.out.println("Set--->"+setNames);
 
//Immutable Map 
Map<String, String> mapNames = Map.ofEntries(
Map.entry("1", "Shailesh"),
Map.entry("2", "Bangalore"),
Map.entry("3", "USA"), 
Map.entry("3", "Dubai"), 
System.out.println("Map---->"+mapNames); 
  }
}

Output:
List-->[Shailesh, Bangalore, USA, Dubai]
Set--->[Dubai, USA, Bangalore, Shailesh]
Map---->{1=Shailesh, 3=USA, 2=Bangalore, 4=Dubai}


Stream API Improvements

Java 9 has introduced two new methods to interact with Streams i.e. takeWhile / dropWhile methods. Additionally, it has added two overloaded methods i.e. ofNullable and iterate methods.
 Improvements are:
1) Limiting Stream with takewhile() and dropwhile() method


public class LimitStream
  public static void main(String[] args) { 
  System.out.println("Java 9 Version--->takeWhile method");
  System.out.println("**************"); 
  List<String> alphabets = List.of("Shailesh", "Shriman","Anish", "Shilpa", "Naz", "Chandan",  "Balaji"); 
  System.out.println("List for takeWhile--->"+alphabets);
  System.out.println("**********************************************************); 
  List<String> subset1 = alphabets.stream().takeWhile(s -> !s.equals("Anish"))
          .collect(Collectors.toList());
  System.out.println(subset1);   
  System.out.println("===========================");
  System.out.println("Java 9 Version--->dropWhile method");
  System.out.println("**************"); 
  System.out.println("List for dropWhile--->"+alphabets);
  System.out.println("**********************************************************); 
  List<String> subset2 = alphabets.stream().dropWhile(s -> !s.equals("Anish"))
          .collect(Collectors.toList()); 
  System.out.println(subset2); 
  }
}


Output:
Java 9 Version--->takeWhile method
**************
List for takeWhile--->[Shailesh, Shriman, Anish, Shilpa, Naz, Chandan, Balaji]
*********************************************************************************
[Shailesh, Shriman]
===========================
Java 9 Version--->dropWhile method
**************
List for dropWhile--->[Shailesh, Shriman, Anish, Shilpa, Naz, Chandan, Balaji]
*********************************************************************************
[Anish, Shilpa, Naz, Chandan, Balaji]

2) Overloaded Stream Iterate() method

public class StreamCheckIterateFor9 {
  public static void main(String[] args) { 
 
  System.out.println("Java 8 Iteration");
  System.out.println("*****************"); 
  List<Integer> numbers = Stream.iterate(1, i -> i+1)
                .limit(10)
                .collect(Collectors.toList());
  System.out.println(numbers);  System.out.println("==========================");
  ////// Java 9 //////////
  System.out.println("Java 9 Iteration");
  System.out.println("*****************");
  List<Integer> numbersss = Stream.iterate(1, i -> i <= 10 ,i -> i+1)
                .collect(Collectors.toList());
  System.out.println(numbersss);
  }
  }

Output:
Java 8 Iteration
*****************
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
=================
Java 9 Iteration
*****************
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3) Insert NULL value in a stream using ofNullable() method


public class StreamCheckNullable9 {
  public static void main(String[] args) {
 
  /////// Java 9 New Stream ofNullable() method//////////
 
/*
 * Until Java 8, you cannot have null value in a stream.
 * It would have caused NullPointerException.
 * In Java 9, the ofNullable method lets you create a single-element stream
 * which wraps a value if not null, or is an empty stream otherwise.
 */ 
 
  Stream<String> stream = Stream.ofNullable("123");
  System.out.println(stream.count());
  stream = Stream.ofNullable(null);
  System.out.println(stream.count());
 
  }
}

Output:
1
0


Other Features will be updated soon.......









Comments

Popular posts from this blog

Java Coding Best Practices

Docker to ELK