Java gets going with version 8

Refurbishment

Article from Issue 163/2014
Author(s):

In mid-March, Oracle released the eighth version of Java. In addition to small tweaks, the long-awaited release extends the core language, adding elements of functional programming – the first significant development since Java 5.

After two and a half years of work, long-serving Java development chief Mark Reinhold released version 8 of Java in March. Not only does it contain minor enhancements to the runtime library, it sees functional elements enter the Java universe in the form of lambdas.

Postponed

Development of the new version was fraught with the same kind of issues as were experienced in the previous release: In August 2010, Reinhold pulled the ripcord and reduced the planned Java 7 feature scope so it could be completed in July 2011. The postponed features were due in version 8 at the end of 2012, which eventually became the beginning of 2014 – again with a reduced feature set.

The reason for the delay was mainly the much needed improvement of the security deficiencies in applets and Java Web Start [1]. The language and Java Runtime Environment (JRE) were actually planned from the beginning to prevent malicious code from breaking out of the designated sandbox, but the implementation of the concepts had significant weaknesses, so many Windows users made the unwelcome acquaintance of the BKA ransomware installed by a Java applet [2].

In particular, the planned modularization of JRE fell victim to the work of plugging security gaps (Project Jigsaw) [3]. Thanks to the ARM port, Java now runs smoothly on the Raspberry Pi, but you can hardly imagine an application on this little computer needing the entire Java standard library, including the Corba stack and LDAP support. With Jigsaw, the developers were also able to limit the runtime environment to the extent actually needed, thereby reducing the scope of the installation and the start time.

Lambdas

Programming languages are also fashion victims, and functional programming is currently gaining more and more followers. Unlike object-oriented languages, the focus here is on functions. Not only can they be defined and executed in the context of a class, but they represent a distinct entity. The programmer can pass them on and link them with other functions. Martin Odersky from ETH Lausanne has shown with his Scala [4] language what the combination of functional and object-oriented features in a single language can look like and do. In Java 8, these ideas are realized directly in the host language Java. In conjunction with its brief syntax, many tasks become much more compact than was previously possible in Java.

Java was designed from the ground up as an object-oriented language, so methods cannot simply be promoted to full-fledged language members like objects. In the background, therefore, minimal objects with only one method are used, and the process of writing them is expedited by the Lambda syntax.

The basis for implementation is the functional interface (FI). FunctionalInterface is an annotation for an interface with a method that represents, so to speak, the bridge between the object and the functional world. For example, Java 8 uses it in its well-known Comparator interface (Listing 1).

Listing 1

Java Comparator with FI

01 package java.util;
02
03 // Java 8: Definition as a FunctionalInterface
04 @FunctionalInterface
05 public interface Comparator<T> {
06
07     // This is THE method in the FunctionalInterface
08     int compare(T o1, T o2);
09
10     //Java 8: Static methods with implementation in the interface
11      public static <T, U> Comparator<T> comparing(
12             Function<? super T, ? extends U> keyExtractor,
13             Comparator<? super U> keyComparator)  {
14         [...]
15     }
16      // Java 8: Default implementation in the interface
17     default Comparator<T> reversed() {
18         return Collections.reverseOrder(this);
19     }
20 }

In previous versions of Java, at least one anonymous class is required to implement the interface (Listing 2, lines 4-9); in the worst case, the programmer defines the comparator in a separate class. This involves rather a lot of typing, whereas the actual computation in the example is no more than the code o1.width - o2.width. The Lambda notation in line 13 makes the whole thing much more compact. The following one-liner

ints.sort((Rectangle r1, Rectangle r2)-> r1.width - r2.width );

defines a comparator class with a sorting function and applies it to the list.

Listing 2

Lambdas in Java 8

01 List<Rectangle> foursides = [...]
02
03  // Java 1-7: Anonymous, inner class
04 Comparator<Rectangle> compr7 = new Comparator<Rectangle>() {
05     @Override
06     public int compare(Rectangle o1, Rectangle o2) {
07         return o1.width - o2.width;
08     }
09 };
10 foursides.sort (compr7);
11
12 // Java 8: Short definition as a Lambda
13 foursides.sort( (Rectangle r1, Rectangle r2) -> r1.width - r2.width);
14 foursides.sort( (r1, r2) -> r1.width - r2.width);
15
16 // Java 8: Use of static methods and references
17 foursides.sort(Comparator.comparingDouble(Rectangle::getWidth));
18 // Java 8: Use of default implementation from interface
19 foursides.sort(Comparator.comparingDouble(Rectangle::getWidth).reversed().
20         thenComparing(Comparator.comparingDouble(Rectangle::getHeight)));

A lambda function is defined in three parts: first the definition of the input parameters (Rectangle r1, Rectangle r2); then the so-called burger arrow (->), and finally the actual method implementation r1.width - r2.width. A method name is not necessary; after defining the Collection.sort method, the compiler already knows which FunctionalInterface fits the bill, and the FI in turn can contain only one method.

Java can also take the type definition for the input parameters from the interface so that the whole thing can be written in a more compact way, as shown in line 14. This reduces the original 155 characters to just 42.

Prepackaged Meal

As illustrated by java.util.Comparator (Listing 1), FunctionalInterface has been added throughout the standard library. In addition to the Lambdas, the syntax for Java 8 has been extended by two additional features: static methods defined in the interface and in the default implementation.

An example of the static method definition is shown in line 17 of Listing 2 The Lambda definition of the comparator from line 14 is nice and short, but you already know how to compare two numbers, so you don't need to reinvent the wheel to do that.

A ready-made implementation for this kind of trivial task can be defined as a static method in the interface in Java 8. The developer needs to tell the method how to access the numbers to be compared. In turn, this occurs as a Lambda function because, with the new syntax, you can also define method references.

The Rectangle::getWidth notation in Listing 2 refers to the getWidth method of the Rectangle class. The code applies this to any Rectangle objects passed into it, to compute the double values. The rules for sorting come from the comparator's static interface method, comparingDouble.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Kotlin Programming Language

    Kotlin, a small island in the Gulf of Finland, is also the name of a new programming language that aims to become a modern alternative to Java.

  • CoffeeScript

    Through the years, many languages have tried to improve or even replace JavaScript, including CoffeeScript, which runs in all JavaScript Runtime Environments and compiles into JavaScript.

  • AJAX Workshop

    Books were the original model for website design. Navigation was similar to flipping the pages. Thanks to AJAX, many state-of-the-art websites now behave like desktop applications.

  • Google Web Toolkit

    The Ingenious Google Web Toolkit builds optimized JavaScript applications in a hurry.

  • Google Dart

    The Dart programming language is Google’s modern alternative to JavaScript. It will mainly run in browsers but can also be used at the command line and on servers as a replacement for PHP.

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News

njobs Europe
What:
Where:
Country:
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia