Java 8 new features

Java 8 is launched on 18-Mar-2014. Java 8 is packed full of some really exciting features at both the JVM and language level, there are literally dozens of new features. Many of the new additions are under-the-hood improvements either at the compiler, JVM or help-system level.


Lambda expressions:


Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.




(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.




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) ->, 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.


Collections API:


Classes in the new package provide a Stream API to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations.


Performance Improvement for HashMaps with Key Collisions.


Here's a list of the new methods:

 - Iterable.forEach(Consumer)

 - Iterator.forEachRemaining(Consumer)

 - Collection.removeIf(Predicate)

 - Collection.spliterator()


 - Collection.parallelStream()

 - List.sort(Comparator)

 - List.replaceAll(UnaryOperator)

 - Map.forEach(BiConsumer)

 - Map.replaceAll(BiFunction)

 - Map.putIfAbsent(K, V)

 - Map.remove(Object, Object)

 - Map.replace(K, V, V)

 - Map.replace(K, V)

 - Map.computeIfAbsent(K, Function)

 - Map.computeIfPresent(K, BiFunction)

 - Map.compute(K, BiFunction)

 - Map.merge(K, V, BiFunction)

 - Map.getOrDefault(Object, V)


The addition of List.sort(Comparator) is fantastic. Previously, the way to sort an ArrayList was this:

Collections.sort(list, comparator);



New Date time APIs:


The new date/time API in Java 8 is contained in the java.time package. If you're familiar with Joda Time, it will be really easy to pick up. Actually, I think it's so well-designed that even people who have never heard of Joda Time should find it easy to pick up.


Almost everything in the API is immutable, including the value types and the formatters. No more worrying about exposing Date fields or dealing with thread-local date formatters.

The intermingling with the legacy date/time API is minimal. It was a clean break:

 - Date.toInstant()

 - Date.from(Instant)

 - Calendar.toInstant--


The new API prefers enums over integer constants for things like months and days of the week.

So, what's in it? The package-level javadocs do an excellent job of explaining the additional types. I'll give a brief rundown of some noteworthy parts.


Extremely useful value types:

 - LocalDateTime, LocalDate, LocalTime

 - Year, Month, YearMonth, MonthDay, DayOfWeek (ok, maybe Year is a little less useful than the others)


Less useful value types:

 - Instant - similar to java.util.Date

 - ZonedDateTime, ZoneId - for when time zones are important

 - OffsetDateTime, OffsetTime, ZoneOffset - for dealing with offsets from UTC

 - Duration, Period - although if you're trying to find the amount of time between two dates, you might be looking for ChronoUnit instead (see below)


Other useful types:

 - DateTimeFormatter - for converting datetime objects to strings

 - ChronoUnit - for figuring out the amount of time bewteen two points, e.g. ChronoUnit.DAYS.between(t1, t2)

 - TemporalAdjuster - e.g. date.with(TemporalAdjuster.firstDayOfMonth())


The new value types are, for the most part, supported by JDBC. There are minor exceptions, such as ZonedDateTime which has no counterpart in SQL.




Unicode Enhancements, including support for Unicode 6.2.0

Adoption of Unicode CLDR Data and the java.locale.providers System Property

New Calendar and Locale APIs

Ability to Install a Custom Resource Bundle as an Extension




For sandbox applets and Java Web Start applications, URLPermission is now used to allow connections back to the server from which they were started. SocketPermissionis no longer granted.


The Permissions attribute is required in the JAR file manifest of the main JAR file at all security levels.


IO and NIO:


New SelectorProvider implementation for Solaris based on the Solaris event port mechanism. To use, run with the system property java.nio.channels.spi.Selectorset to the value


Decrease in the size of the <JDK_HOME>/jre/lib/charsets.jar file


Performance improvement for the java.lang.String(byte[], *) constructor and thejava.lang.String.getBytes() method.


java.lang and java.util packages:


Parallel Array Sorting

Standard Encoding and Decoding Base64

Unsigned Arithmetic Support




Classes and interfaces have been added to the java.util.concurrent package.


Methods have been added to the java.util.concurrent.ConcurrentHashMap class to support aggregate operations based on the newly added streams facility and lambda expressions.


Classes have been added to the java.util.concurrent.atomic package to support scalable updatable variables.


Methods have been added to the java.util.concurrent.ForkJoinPool class to support a common pool.


The java.util.concurrent.locks.StampedLock class has been added to provide a capability-based lock with three modes for controlling read/write access.




The class has been added.

In the class, if a security manager is installed, calls that request to open a connection require permission.




The JDBC-ODBC Bridge has been removed.

JDBC 4.2 introduces new features.


Java + JavaScript:

Java 8 is looking to right one of its biggest historical wrongs – the ever growing distance between Java and JavaScript, one that has only increased in the past few years. With this new release, Java 8 is introducing a completely new JVM JavaScript engine – Nashorn. This engine makes unique use of some of the new features introduced in Java 7 such as invokeDynamic to provide JVM-level speed to JavaScript execution right there with the likes of V8 and SpiderMonkey.


This means that the next time you’re looking to integrate JS into your backend, instead of setting up a node.js instance, you can simply use the JVM to execute the code. The added bonus here is the ability to have seamless interoperability between your Java and JavaScript code in-process, without having to use various IPC/RPC methods to bridge the gap.


Type Annotation:


Now annotations can be used to decorate generic types itself.


	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.


Functional Interfaces:


These interfaces(java.util.function) 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.