Friday, January 24, 2014

Java Reinvented | Salient Features of Java 8 | Part 1

Java 8 Salient Features

The 2013 Java One keynote says, "Java is Back'. Not only is it back, it is new, it is easier to read, and at the same time it is difficult to learn, specially if you are used to coding in Java. Multiple brilliant features have been added in Java 8, a quick introduction of 52 features was presented at Devoxx and is available at Parleys.

This blog is first part of a series on some of the features that I believe would be of significant value to everyday developer. Most of them are related to lambda expressions itself, which is going to significantly alter coding in Java. The following will be covered:
  1. Lambda Expressions
  2. Default Methods
  3. Functional Interface
  4. Streams and Bulk Collections
  5. Date and Time API
  6. Base 64 Encoding Schemes
  7. Permgen removed, permanently
Lambda Expressions
Also known as closures, a lambda expression is an anonymous method - has an argument list, a return type and a body. A lambda expression looks like a problem statement and hence code is much easier to understand. eg, to print names of all male employees whose first name contains letter 'n', sorted by their names, the following code can be used.


As you can see, re-written in Lambda, code becomes so much simpler. Additionally, instead of two "for Each" passes, lambda code needs a single pass (with some caveats).

Default Methods
Modifying an existing, widely used, mature language like Java is no easy task. So when Java developers were working on lambda expressions, they faced a wall in extending existing well known packages. The solution came through modifying interface contract to support providing default implementation of a method within interface itself. Adding default methods in an interface is source and binary compatible.

A default method is also known as defender method or virtual extension method. The following image shows clip of Iterable interface in JDK 8. As you can see, the "remove" method is now "default" allowing developers to not implement it in their classes that implement Iterable interface.












An additional method "forEachRemaining" has been added (details suppressed for brevity), allowing existing implementation to not be broken by addition of new method.

Java folks say developers would not need to worry about diamond problem due to this, as this adds behaviour inheritance only, and not data inheritance - that usually causes issues. Additionally, as earlier, compile time checks prevent a class from implementing two interfaces with same method.

Adding behaviour (methods) to definition (interface) may not be a really good idea, but hopefully this will resolve more problems than it creates.

Look out for the next post, showing examples of more features. All references will be part of last post :)