How JAVA 9 Is A better approach to JAVA 8
Posted By : Sudhakar Pandey | 30-Oct-2017

Recentely oracle launches java 9. You can download from here also http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.html
Java 9 have very special features and also have improvements of java 8 stream methods.
Java 9 features listed below as -
1- The Java Shell (REPL)
2- Private methods in interfaces
3- Factory methods for collections
4- Try with resources enhancements
5- Enhancements of Java 8 Stream API
6- The java plateform Module systems
7- Diamond Operator
8- SafeVarargs Annotation
9- Process API updates
10- HTTP/2 Client
11- G1 Garbage collector
1- The Java Shell (REPL): This is not new features in programming languages world, many languages already supports this features. Anyone can achieve jshell feom console after insatll Java 9 jdk. This is a great tool to explore API and also can help in test other java APIs. With the use of this no need to write hole class for test java function( No need to write public static void main(String[] args)). It also increases developers productivity.
2- Private methods in interfaces: As we achieve functionality of default methods in Java 8. An interfaces can also have defined methods not only methods signatures. But we cann't make private this default methods. Due to this we need to create another default methods. After Java 9, we can add private methods with interfaces for this problem-
public interface DemoInterface {
void normalMethod();
default void methodWithDefault() { init(); }
default void anotherDefaultMethod() { init(); }
// This method is not part of the public API exposed by DemoInterface
private void init() { System.out.println("Its a java 9 features..."); }
}
If we are using APIs with default methods, private interface methods helpful in designing their implementation.
3- Factory methods for collections: As of now If we want to create immutable java collection before java 9 then we used traditional way like below- Ex-
Setset = new HashSet<>(); set.add("oodles"); set.add("technologies"); set.add("bitcoin"); set = Collections.unmodifiableSet(set);
This looks like too much tasks for adding elements one by one, now we can add like below-
Listlist = Arrays.asList("oodles", "technologies", "bitcoin"); // adding all element in single line.
However this List is better than the constructor initialisation- We can also reduce statements like the double-brace technique:
Setset = Collections.unmodifiableSet(new HashSet () {{ add("oodles"); add("technologies"); add("bitcoin");}})
or by using Java 8 Streams:
Stream.of("oodles", "technologies", "bitcoin").collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
If we want to create collections in your code and directly initialize it with some elements. We must write repetitive code where you instantiate the collection, followed by adding several `add` calls. In java 9 we can write it easily -
Setints = Set.of("oodles", "Technologies", "Bitcoin"); List strings = List.of("Oodles", "Technologies");
With this functionality we can write immutables collections, if we are going to add elements after creating it results in as 'UnsupportedOperationException'.
4- Try with resources enhancements: In Java 7, already Try-With-Resources introduced. With this it automatically manage resources using an AutoCloseable interfaces, we have not needed to close resources explicitly. As there is favourable condition where we write code for close database connection in finally block. ex-
public void exampleForDbCon() throws SQLException {
Connection conn = DriverManager.getConnection("urlname", "usernameForDB", "passwordForauthenticate");
try (ResultSet rs = conn.createStatement().executeQuery("select id,name,address from user")) {
while (rs.next()) {
System.out.println("Using exampleForDbCon() :::: " + rs.getString(1));
}
} catch (SQLException ex) {
System.out.println("Exception from DB :::: " + ex.getMessage());
} finally
if (null != conn)
conn.close();
}
}
But in Java 9 -
public void exampleForDbCon() throws SQLException {
Connection conn = DriverManager.getConnection("urlname", "usernameForDB", "passwordForauthenticate");
try (conn; ResultSet rs = conn.createStatement().executeQuery("select id,name,address from user")) {
while (rs.next()) {
System.out.println("Using exampleForDbCon() :::: " + rs.getString(1));
}
} catch (SQLException ex) {
System.out.println("Exception from DB :::: " + ex.getMessage());
}
}
In this try block we put conn object inside try-with-resource block, so resource as effectively final or final variable can be put into try-with-resource blocks and would be eligible for automatic resource management.
5- Enhancements of Java 8 Stream API: Java 8 stream contains iterate method, which have two arguments- initializer (is called seed) and function to be applied to the previous element to produce the new element. This method have not termination of that loop. Ex- Below statment starts and never will terminate and continue executing.
Stream.iterate(1, count->count+2 ).forEach(System.out::println);
The newer Java 9 update the iterate method. This is the replacement of for loops. This method is solution of above methods-
iterate(initialize section; predicate section(hasNext); next section)
Above method will stop once the hasNext section returns false. The newer version of Java 9 introduced ofNullable method to return empty Optionals if the value is null. This removes the possibility of NullPointerException and avoid having null checks everywhere. In previous version -
User user= getUser(userId); Streamroles= user== null? Stream.empty(): user.roles();
In above getUser method can return null, So we can prevent and handled null check. In the newer version java -
User user= getUser(userId);
Stream.ofNullable(user).flatMap(User::roles)
In the above example use of ofNullable utility to reduce the loc.
Thanks
I hope this will be helpful.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sudhakar Pandey
Sudhakar pandey is java developer and passoinate about learning to new technology, He have exposure about spring, hibernate, REST services, Multithreading , JSP/ Servlet. On the database side He have exposure about MySql, Oracle, Postgres.