Core Java

8 new features for Java 8

NOTE: Make sure to also check our detailed tutorial Java 8 Features – The ULTIMATE Guide.

Jdk 1.8 aka, Java 8 is launched today meaning that the General Availability release of it is out in the open and developers can switch from Early Release releases to a tested release for production use. But what does it means for you, the busy Java developer? Well, here are some points that I condensed to mark this release:

1.Lamda Expressions

I started with lambda expressions as this is probably the most sought after feature in the language after probably Generics/Annotations in Java 5.

Here’s the syntax:

(argtype arg...) -> { return some expression.. probably using these arguments }

What it does is that it reduces the code where it is obvious, such as in an anonymous innerclass. (Swing action handlers just got sexy, yay!)

So, a thread can be changed as:



Runnable oldRunner = new Runnable(){
    public void run(){
        System.out.println("I am running");
    }
};
Runnable java8Runner = () ->{
    System.out.println("I am running");
};

Similar to Scala, type inference is also possible in Lambdas. Consider the following available example:

Comparator c = (a, b) -> Integer.compare(a.length(), b.length());

Here, the types of a,b (In this case String, from the Comparator interface) are inferred as the compare method is implemented.

The symbol used to separate the block from arguments, -> is quite similar to => already used in Scala and if you are good at it, there is not much reason to switch as you will feel the way lambdas are implemented in java is inadequate(and verbose), but for a good ‘ol java programmer, this is the way to go.

2.Generic Type changes and improvements

Taking clues from Lambdas, generic collections can also infer the data types to be used to an extent. The methods for instance using a generic collection need not specify genric types. Hence, the following method

SomeClass.method();

Can be called simply ignoring the type information:

SomeClass.method();

The type can be inferred by the method signature, which is helpful in nested calls like

myCollection.sort().removeUseless().beautify();

3. Stream Collection Types (java.util.stream)

A stream is a iterator that allows a single run over the collection it is called on. Along with Lambdas, this is another noteworthy feature to watch out for. You can use streams to perform functional operations like filer or map/reduce over collections which can be streamed as individual elements using Stream objects. Streams can run sequentially or parallely as desired. The parallel mode makes use of fork/join framework and can leverage power of multiple cores.

Example:

List guys = list.getStream.collect(Collectors.toList())

can also be implemented parallely as

List guys = list.getStream.parallel().collect(Collectors.toList() 

Another nice example that reduces the collection to a single item is by calling reduce algorithem.

int sum = numberList.stream().reduce(0, (x, y) -> x+y);

or,

int sum = numberList.stream().reduce(0, Integer::sum);

4. Functional Interfaces (java.util.function)

These interfaces contain some default methods which need not be implemented and can run directly from the interface. This helps with existing code – changing interfaces need not make all the classes implementing it implement new methods. This is similar to Traits in Scala and functional interfaces will be compatible with lambdas.

5. Nashorn – The Node.js on JVM

This is the javascript engine that enables us to run javascript to run on a  jvm. It is similar to the V8 engine provided by chrome over which Node.js runs. It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server. This is exciting to say at the least as it marries scalability and asynchronous nature of Node.js with safe and widespread server side Java middleware directly.

6. Date/Time changes (java.time)

http://download.java.net/jdk8/docs/api/java/time/package-summary.html

The Date/Time API is moved to java.time package and Joda time format is followed. Another goodie is that most classes are Threadsafe and immutable.

7. Type Annotations

Now annotations can be used to decorate generic types itself.

Eg:

List<@Nullable String>

which is not desired always, but can prove to be useful in certain circumstances. Apart from decorating Generic types, it can also be used in constructors and casting.

new @NonEmpty @Readonly List(myNonEmptyStringSet)
new @Interned MyObject()

myString = (@NonNull String) myObject;

Even the array objects can be annoted:

@NotNull String[] arr;

The inclusion of RuntimeVisibleTypeAnnotations and RuntimeInvisibleTypeAnnotations attributes which cause the .class file to save the annotation information.

8.Other – (nice to have) Changes

Reflection api is slightly increased with the support of TypeName, GenericString, etc.

String.join() method is a welcome addition as a lot of self created utility classes are created instead. So, the following example

String abc= String.join(" ", "Java", "8");

Will get evaluated as “Java 8”.

In the Collections package, the Comparator interface is revamped and methods like reversed, comparing and thenCOmparing have been added which allow easy customization of comparison over multiple fields. Other libraries like the Concurrency and NIO have also been updated but is nothing noteworthy for following up and is keeping with the changes in the api.

Overall, Java8 is well thought of and is making mainstream java concise and picking some good parts of Scala/Clojure for the improving its syntax and addressing much sought features.

Reference: 8 new features for Java 8 from our JCG partner Sumit Bisht at the Sumit Bisht blog blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Himansh bisht
Himansh bisht
8 years ago

Hi Sumit ,

Great Article !!!!!!! Can i find more practical examples that would be plus.

karthick
karthick
8 years ago

Easy to understand.

tony
tony
8 years ago

when did java jump the shark ? 100 different ways to do a simple task is NOT a good thing….just make java faster and give us kick butt libraries connecting to new technologies (big data, robotics, …) no need to reinvent the core syntax of the language, but geeks will ruin too much of a good thing…did texting make english better ?

MNagy
MNagy
8 years ago

I saw that on many post and still not get it: (with all respect) you are using the term functional interfaces all wrong. It refers to good’ol java interfaces with one method which intended to bring functions to a more important citizen in the Java word: thus make it possible to apply functional programming. What you are describing there are default methods which is a different concept.
I heard this from few collegues as well I sow you are not alone — how could this get so viral :)

Injector
Injector
8 years ago
Abhijeet
Abhijeet
8 years ago

More precise insights on difference about them is available on http://way2java.com/java-versions-2/jdk-1-8-features/ link.
Suggest reading it for functional interface.

Anirban Konar
Anirban Konar
8 years ago

Nice summary, very clear and easy to understand

J. Fred Muggs
J. Fred Muggs
7 years ago

” Hence, the following method

SomeClass.method();

Can be called simply ignoring the type information:

SomeClass.method();”

So…an improvement in Java 8 is that something is now the same thing it always was? Really?

This is less than useful, even correcting for the misspelled words and inconsistent usage.

Back to top button