Like Java 7 ? Then You Are Going to Love Java 8 !!


JAVA 8 (aka jdk 1.8) is a major release of JAVA programming language development. With the Java 8 release, Java provided support for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc. which will be discussed in detail.
In this blog, we will focus on What’s New in Java 8 and it’s usage in a simple and intuitive way.We assume that you are already familiar with Java 7.

If you want to run programs in Java 8, you will have to setup Java 8 environment by following steps :

  1. Download JDK8 and install it. Installation is simple like other java versions. JDK installation is required to write, compile and run the program in Java.
  2. Download latest Eclipse IDE/IntelliJ , these provide support for java 8 now. Make sure your projects build path is using Java 8 library.

1

New Features

There are dozens of features added to Java 8, the most significant ones are mentioned below . Let’s Begin Discussing Each in Detail :

Lambdas

Lambda expressions are introduced in Java 8 and are considered to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot.

A lambda expression is characterized mostly by the following syntax −

parameter -> expression body

For Example :

If we have a Interface addable as :

interface Addable { 
int add(int a,int b);
}

So we can use it as :

public class LambdaExample{
public static void main(String[] args){
Addable ad1=(a,b)->(a+b);  
System.out.println(ad1.add(10,20));  // output will be 30
}
}

Functional Interfaces

 

A core concept introduced in Java 8 is that of a “functional interface”. An interface is a functional interface if it defines exactly one abstract method. Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).
We usually annotate @FunctionalInterface  at the beginning of an interface to ensure that it is functional interface. This annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces.
java.lang.Runnable with single abstract method run() is a great example of functional interface.

One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate them .Each lambda corresponds to a given type, specified by an interface. A so called functional interface must contain exactly one abstract method declaration. Each lambda expression of that type will be matched to this abstract method.

Example :
We can use a converter interface which is a functional interface

@FunctionalInterface
interface Converter<F, T> {
    T convert(F from);
}
Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("123");
System.out.println(converted);    // Ouput : 123

Method References

Java 8 Method reference is used to refer method of functional interface . It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

There are four types of method references:

  1. Reference to a static method.
  2. Reference to an instance method of a particular object.
  3. Reference to an instance method of an arbitrary object of a particular type.
  4. Reference to a constructor.
interface Sayable{  
    void say();  
}  

public class MethodReference {  

    public static void saySomething(){  
        System.out.println("Hello, this is static method.");  
    }  

    public static void main(String[] args) {  
        // Referring static method  
        Sayable sayable = MethodReference::saySomething;  
        // Calling interface method  
        sayable.say();  
    }  

}

Optional Class

Java introduced a new class Optional in Java 8. .Optional is a simple container for a value which may be null or non-null. It is a public final class which is used to deal with NullPointerException in Java application.
We must import java.util package to use this class. It provides methods to check the presence of value for particular variable Think of a method which may return a non-null result but sometimes return nothing. Instead of returning null you return an Optional in Java 8.

Example :

Optional<String> optional = Optional.of("hello");

optional.isPresent();           // true
optional.get();                 // "hello"
optional.orElse("fallback");    // "hello"

optional.ifPresent((s) -> System.out.println(s.charAt(0))); // h

Streams

A java.util.Stream represents a sequence of elements on which one or more operations can be performed. Streams are created on a source, e.g. ajava.util.Collection like lists or sets.

Stream provides following features:

  • Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.
  • Stream is functional in nature. Operations performed on a stream does not modify it’s source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.
  • Stream is lazy and evaluates code only when required.
  • The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

Stream operations can either be executed sequential or parallel.
Collections in Java 8 are extended so you can simply create streams either by callingCollection.stream() or Collection.parallelStream().

Operations on Streams : 

1. Intermediate Operations  :

  • 3filter
  • map
  • distinct

2. Terminal Operations :

  • forEach
  • collect
  • reduce

Basic Example :

 public static void main(String[] args) {
        Stream<Integer> number = Stream.of(1, 2, 3, 4, 5);
        List<Integer> result2 = number.filter(x -> x!= 3).collect(Collectors.toList());
        result2.forEach(x -> System.out.println(x)); // Output : 1,2,4,5
    }

Default And Static Methods

From Java 8, interfaces are enhanced to have method with implementation. We can use default and static keyword to create interfaces with method implementation.
Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.

@FunctionalInterface
public interface Interface1 {

	void method1(String str);
	
	default void log(String str){
		System.out.println("I1 logging::"+str);
	}
	
	static void print(String str){
		System.out.println("Printing "+str);
	}
}
//valid because static and default methods are valid in Functional interface

New Date/Time API

With Java 8, a new Date-Time API is introduced to cover the following drawbacks of old date-time API −

  • Not thread safe
  • Poor design
  • Difficult time zone handling

Java 8 introduces a new date-time API under the package java.time. Following are some of the important classes introduced in java.time package −

  • Local − Simplified date-time API with no complexity of timezone handling.
  • Zoned − Specialized date-time API to deal with various timezones.
LocalDateTime currentTime = LocalDateTime.now();
      System.out.println("Current DateTime: " + currentTime);

// Output :: Current DateTime: 2017-06-19T11:00:45.457
 Month month = currentTime.getMonth();
      int day = currentTime.getDayOfMonth();
      int seconds = currentTime.getSecond();
		
      System.out.println("Month: " + month +" day: " + day +" seconds: " + seconds);
Month: JUNE day: 19 seconds: 45

Completable Futures

The CompletableFuture is a Future that can have it’s value explicity set and more interestingly can be chained together to support dependent actions triggered by the CompletableFutures completion.

This way we can build systems in a non-blocking fashion.

Future.get() is the most important method. It blocks and waits until promised result is available.

Example :

final Future<String> contentsFuture = startDownloading(new URL("http://www.example.com"));

while (!contentsFuture.isDone()) {

askUserToWait();
doSomeComputationInTheMeantime();

}
contentsFuture.get();

The last call to contentsFuture.get() is guaranteed to return immediately and not block because Future.isDone() returned true.

 

To sum up the the whole , These were some of the new additions to the Java successor i.e. Java 8 and with Java 9 being on its way many new things are in store.

To get More information about Java 8 please refer to the Official Site for Java 8.


knoldus-advt-sticker


 

Advertisements
This entry was posted in Functional Programming, Java and tagged , , , , , , . Bookmark the permalink.

7 Responses to Like Java 7 ? Then You Are Going to Love Java 8 !!

  1. Anmol Sarna says:

    Reblogged this on Anmol Sarna and commented:
    New to Java 8? Here’s Where You can Start.

  2. Pingback: Did Someone Say Java 9 ?? | Knoldus

  3. Dav Vendator says:

    Really Enjoyed Reading it.Very informative.However I have one suggestion for you I think you should put code snippets in code tags rather than block quotes . Everything else is good.peace out

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s