fbpx
Select Page

Java 9 Features and Enhancements

1) JShell: the interactive Java REPL

REPL stands for Read-Eval-Print-Loop. Many languages in today’s world have already implemented this policy and Java now has started building an application on this. Jshell is the language that works on REPL policy which is executed on console and we can directly start typing and executing Java code. The faster feedback of jshell makes it an effective tool to explore APIs and try out other language features.

E.g.: –

 jshell> 2+3  

$1 ==> 5  

| created scratch variable $1int  

Compound Expression 

jshell> 2+(5*4+(2+1))  

$4 ==> 25  

| created scratch variable $4int  

jshell>  

Methods

jshell> void show () {  

   …> System.out.println(“This is show method”);  

   …> }  

| created method show ()  

Class:

jshell> class Hello {  

   …> void show () {  

   …> System.out.println(“This is show method”);  

   …> }  

   …> }  

| created class Hello  

  jshell> new Hello (). show ();  

This is show method  

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

2)  Collection factory methods: –

 To create a collection (e.g., a List or Set) in your code and to directly add it with some elements that will lead to redundant code where you instantiate the collection, followed by several `add` calls. With Java 9, several types of collection factory methods have been added:

Eg:

Set<Integer> ints = Set. of (1, 2, 3);

List<String> strings = List. of (“first”, “second”);

This type of factory method being shorter and nicer to read, these methods also relieve you from having to implement a specific collection implementation. 

3)  Private methods inside Interfaces: –

In Java 9, we can have private methods inside an interface. Interface allows us to create private methods that help to share common code between non-abstract methods.

E.g.:

interface Sayable { 

 default void says () {

      saySomething ();  

    }  

    // Private method inside interface  

    private void saySomething () {  

        System.out.println(“Hello… I’m private method”);  

    }  

}  

public class PrivateInterface implements Sayable {  

    public static void main (String [] args) {  

        Sayable s = new PrivateInterface ();  

        s.says ();  

    }  

}  

Output:

Hello… I’m private method

The need for Private Methods:

While using default methods, the number of duplicate codes can increase which in turn increases the length of code and can reduce the code reusability. In the following example, we will see how private methods can decrease the generation of duplicate code.

Example1: Without Private Method:

interface MyInterfaceInJava8 {

   default void method1() {

System.out.println(“Starting method”);

System.out.println(“Doing something”);

System.out.println(“This is method1”);

   }

   default void method2() {

System.out.println(“Starting method”);

System.out.println(“Doing something”);

System.out.println(“This is method2”);

   }

}

public class Java Example implements MyInterfaceInJava8{

   public static void main (String args []) {

JavaExample je = new JavaExample ();

  1. method1();
  2. method2();

   }

}

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

Example 2: With Private Methods:

interface MyInterfaceInJava9 {

   default void method1() {

//calling private method

printLines ();

System.out.println(“This is method1”);

   }

   default void method2() {

//calling private method

printLines ();

System.out.println(“This is method2”);

   }

   private void printLines () {

System.out.println(“Starting method”);

System.out.println(“Doing something”);

   }

}

public class JavaExample implements MyInterfaceInJava9{

   public static void main (String args []) {

JavaExample je = new JavaExample ();

  1. method1();
  2. method2();

   }

}

Output:

Starting method

Doing something

This is method1

Starting method

Doing something

This is method2

From the above program, we can see that the output is the same but the code size has reduced. 

4) Try with Resources Enhancements: –

 Try with resources feature was first introduced in java 7 and then, later on, was enhanced in Java 9. The following are the details of the improvements which took place in try with resources.

What is Try-with-Resources?

Try with resources came into existence to eliminate the code which we use to write in exception handling inside the final block of closing the resources.

Uses of Try with Resources: 

1)Try with resources closes all the resources implicitly(automatically) like database connection, file closing, network connection etc. No need to close it manually. This saves from occurring memory leak.

2)With the help of try with resources no need to write unnecessary code and makes the code more readable.

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

Example: Try with Resources in java 7 

import java.io. FileNotFoundException;  

import java.io. FileOutputStream;  

public class JavaExample {  

    public static void main (String [] args) throws FileNotFoundException {  

        try (FileOutputStream fileOutputStream = new FileOutputStream(“read.txt”) 😉 { 

             String str = “Java is an OOP Language.”; 

                          //Converting the given string in bytes

             byte bytes [] = str. getBytes ();       

                          //Writing the bytes into the file

             fileOutputStream. write(bytes);      

                      //Displaying success message after the successful write operation

             System.out.println(“Writing done successfully”);           

        } catch (Exception e) {  

            System.out.println(e);  

        }         

    }  

}

Problems in Try with Resources in Java 7

In the above code, the resource is not allowed to be declared outside the statement block. If declared it will throw a compile-time error.

Example: Resource declared outside the Try-with-Resources block.

import java.io. FileNotFoundException;  

import java.io. FileOutputStream;  

public class JavaExample {  

    public static void main (String [] args) throws FileNotFoundException { 

       FileOutputStream fileOutputStream = new FileOutputStream(“read.txt”);

       try(fileOutputStream) { 

             String str = “Java is a OOP Language.”; 

            byte bytes [] = str. getBytes ();       

            fileOutputStream. write(bytes);      

            System.out.println(“Writing done successfully”);           

        } catch (Exception e) {  

            System.out.println(e);  

        }         

    }  

}

To solve this error, we also have a solution to this problem by declaring a duplicate resource as follows:

import java.io. FileNotFoundException;  

import java.io. FileOutputStream;  

public class JavaExample {  

    public static void main (String [] args) throws FileNotFoundException { 

       FileOutputStream fileOutputStream = new FileOutputStream(“read.txt”);

       try (FileOutputStream fileOutputStream2 = fileOutputStream) { 

            String str = “Java is an OOP Language”; 

            byte bytes [] = str. getBytes ();       

            fileOutputStream2.write(bytes);      

            System.out.println(“Writing done successfully”);           

        } catch (Exception e) {  

            System.out.println(e);  

        }         

    }  

}

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

Try with Resource Enhancements in Java 9

Java 9 provides major changes in try with the resource by allowing to declare the resource outside of the try with resource block. There is no need to create the local variable to access the resource.

Following is the code which was same as above which will not give any compile time error as it was fixed.

import java.io. FileNotFoundException;  

import java.io. FileOutputStream;  

public class JavaExample {  

    public static void main (String [] args) throws FileNotFoundException { 

       FileOutputStream fileOutputStream = new FileOutputStream(“read.txt”);

       try(fileOutputStream) { 

            String str = “Java is an OOP Language”; 

            byte bytes [] = str. getBytes ();       

            fileOutputStream.write(bytes);      

            System.out.println(“Writing done successfully”);           

        } catch (Exception e) {  

            System.out.println(e);  

        }         

    }  

}

5) Anonymous Inner classes and Diamond Operator

  • What you mean by diamond operator?

The diamond operator was first introduced in Java 7. The use of the diamond operator was to ignore redundant code by leaving the generic type on the right side of the expression.

//Earlier Java 7 it was compulsory to mention generic type at both the ends.

List<String> myList = new ArrayList<String> ();

// From Java 7, no need to explicitly mention generic type in both the side instead we can use a diamond operator. The compiler can implicitly infer the type.

List<String> myList = new ArrayList<> ();

Following problem arises with diamond operator while working with Anonymous inner classes.

From Java 7 it was allowed to use diamond operator in normal classes but it created a problem in anonymous inner class.

Example:

abstract class MyClass<T> {  

    abstract T add (T num, T num2);  

}  

public class JavaExample {  

    public static void main (String [] args) {  

        MyClass<Integer> obj = new MyClass<> () {  

            Integer add (Integer x, Integer y) {  

                return x+y;   

            }  

        };    

        Integer sum = obj.add (100,101);  

        System.out.println(sum);  

    }  

}

Output:

JavaExample.java:7: error: cannot infer type arguments for MyClass

        MyClass obj = new MyClass<> () {  

                                        ^

  reason: cannot use ‘<>’ with anonymous inner classes

  where T is a type-variable:

    T extends Object declared in class MyClass

We will get a compilation error when we ran the above code in Java 8.

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

Java 9 – Diamond operator enhancements

In Java 9, improvements were introduced in diamond operator and allows us to use the diamond operator with anonymous inner classes. 

Example how enhancements were done while using diamond operator.
Running this code in Java SE 9

abstract class MyClass<T> {  

    abstract T add (T num, T num2);  

}  

public class JavaExample {  

    public static void main (String [] args) {  

        MyClass<Integer> obj = new MyClass<> () {  

            Integer add (Integer x, Integer y) {  

                return x+y;   

            }  

        };    

        Integer sum = obj.add (100,101);  

        System.out.println(sum);  

    }  

}

Output:

201

6) Java 9 – @SafeVarargs Annotation (with examples)

Java 7 introduces a feature called @SafeVarargs annotation to eliminate the unsafe operation warnings that occur when a method is using varargs (variable number of arguments). Earlier till Java 7, the @SafeVarargs annotation was only used with methods (final or static methods or constructors) because they can’t be overridden. The reason was overridden methods can still perform unsafe operation on their varargs.

Java 9 has enhanced the use of @SafeVarargs annotation, i.e. it can now be used with private methods as well which can also cannot be overridden.

import java. util. ArrayList;  

import java. util. List;  

public class JavaExample {  

    @SafeVarargs

    private void print (List… names) {  

        for (List<String> name: names) {  

            System.out.println(name);  

        }  

    }  

    public static void main (String [] args) {  

        JavaExample obj = new JavaExample ();  

        List<String> list = new ArrayList<String> ();  

        list.add(“Kevin”);  

        list.add(“Rick”); 

        list.add(“Negan”);

        obj.print(list);  

    }      

}

Please visit my previous blog to know Features and Enhancement of Java 8.

 

Author:-
Pallavi Kadam Software Trainer
SevenMentor Pvt Ltd.

 

Call the Trainer and Book your free demo Class for JAVA now!!!

call icon

© Copyright 2020 | Sevenmentor Pvt Ltd.

 

Pin It on Pinterest

× How can I help you?