Getting started with Java 8 – Part 1

Java 8 has been the most awaited and is a major feature release of Java. I have tried to cover some of the features in this blog to help you understand various aspects of Java 8.

What is Java 8???

Java 8 is a revolutionary release of the world #1 development platform. It includes a huge upgrade to java programming model and a coordinated evolution of the JVM, Java Language and Libraries.

Let us look through the default methods for interfaces used in Java 8.

Default Methods for Interfaces:-

Java 8 enables us to add non-abstract method implementations to the interfaces by utilizing the default keyword.

Example – This functionality can reduce a lot of code duplication when more than one code has the same implementation.

We can just define it as default and only in case of different implementation override the method.

interface A {
    void method1(int a);

    default void method2(int a) {
        //implementation
    }
}

Any class that implements this interface may or may not implement method2 and it will automatically pick up this implementation if not overridden.

Lambda Expression:-

Let’s see how sorting a list of strings works in prior versions.

List names = Arrays.asList("Waylon", "Justine", "Marcus", "Thalia", "Angela");
Collections.sort(names, new Comparator() {
    @Override
    public int compare(String a, String b) {
        return b.compareTo(a);
    }
});

Now let’s see how we can reduce the above code in a more shorter and more readable form by making use of Java 8.

Collections.sort(names, (a, b) -> b.compareTo(a));

Click here for Part 2

By:
Aditya Agrawal
www.coviam.com

1 thought on “Getting started with Java 8 – Part 1

Leave a Reply

Your email address will not be published.