On Java 8 is only available as an eBook, and only via Google Play Books. Any other source or delivery mechanism is illegitimate.This book is.
Java Platform, Standard Edition 8 is a major feature release. This document summarizes features and enhancements in Java SE 8 and in JDK 8, Oracle's implementation of Java SE 8. Click the component name for a more detailed description of the enhancements for that component.
- 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.
- Method references provide easy-to-read lambda expressions for methods that already have a name.
- Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.
- Repeating Annotations provide the ability to apply the same annotation type more than once to the same declaration or type use.
- Type Annotations provide the ability to apply an annotation anywhere a type is used, not just on a declaration. Used with a pluggable type system, this feature enables improved type checking of your code.
- Improved type inference.
- Method parameter reflection.
- Classes in the new
java.util.stream
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
- Compact Profiles contain predefined subsets of the Java SE platform and enable applications that do not require the entire Platform to be deployed and run on small devices.
- Client-side TLS 1.2 enabled by default
- New variant of
AccessController.doPrivileged
that enables code to assert a subset of its privileges, without preventing the full traversal of the stack to check for other permissions - Stronger algorithms for password-based encryption
- SSL/TLS Server Name Indication (SNI) Extension support in JSSE Server
- Support for AEAD algorithms: The SunJCE provider is enhanced to support AES/GCM/NoPadding cipher implementation as well as GCM algorithm parameters. And the SunJSSE provider is enhanced to support AEAD mode based cipher suites. See Oracle Providers Documentation, JEP 115.
- KeyStore enhancements, including the new Domain KeyStore type
java.security.DomainLoadStoreParameter
, and the new command option-importpassword
for the keytool utility - SHA-224 Message Digests
- Enhanced Support for NSA Suite B Cryptography
- Better Support for High Entropy Random Number Generation
- New
java.security.cert.PKIXRevocationChecker
class for configuring revocation checking of X.509 certificates - 64-bit PKCS11 for Windows
- New rcache Types in Kerberos 5 Replay Caching
- Support for Kerberos 5 Protocol Transition and Constrained Delegation
- Kerberos 5 weak encryption types disabled by default
- Unbound SASL for the GSS-API/Kerberos 5 mechanism
- SASL service for multiple host names
- JNI bridge to native JGSS on Mac OS X
- Support for stronger strength ephemeral DH keys in the SunJSSE provider
- Support for server-side cipher suites preference customization in JSSE
- The new Modena theme has been implemented in this release. For more information, see the blog at fxexperience.com.
- The new
SwingNode
class enables developers to embed Swing content into JavaFX applications. See theSwingNode
javadoc and Embedding Swing Content in JavaFX Applications. - The new UI Controls include the
DatePicker
and theTreeTableView
controls. - The
javafx.print
package provides the public classes for the JavaFX Printing API. See the javadoc for more information. - The 3D Graphics features now include 3D shapes, camera, lights, subscene, material, picking, and antialiasing. The new
Shape3D
(Box
,Cylinder
,MeshView
, andSphere
subclasses),SubScene
,Material
,PickResult
,LightBase
(AmbientLight
andPointLight
subclasses) , andSceneAntialiasing
API classes have been added to the JavaFX 3D Graphics library. TheCamera
API class has also been updated in this release. See the corresponding class javadoc forjavafx.scene.shape.Shape3D
,javafx.scene.SubScene
,javafx.scene.paint.Material
,javafx.scene.input.PickResult
,javafx.scene.SceneAntialiasing
, and the Getting Started with JavaFX 3D Graphics document. - The
WebView
class provides new features and improvements. Review Supported Features of HTML5 for more information about additional HTML5 features including Web Sockets, Web Workers, and Web Fonts. - Enhanced text support including bi-directional text and complex text scripts such as Thai and Hindi in controls, and multi-line, multi-style text in text nodes.
- Support for Hi-DPI displays has been added in this release.
- The CSS Styleable* classes became public API. See the
javafx.css
javadoc for more information. - The new
ScheduledService
class allows to automatically restart the service. - JavaFX is now available for ARM platforms. JDK for ARM includes the base, graphics and controls components of JavaFX.
- The
jjs
command is provided to invoke the Nashorn engine. - The
java
command launches JavaFX applications. - The
java
man page has been reworked. - The
jdeps
command-line tool is provided for analyzing class files. - Java Management Extensions (JMX) provide remote access to diagnostic commands.
- The
jarsigner
tool has an option for requesting a signed time stamp from a Time Stamping Authority (TSA). - The
-parameters
option of thejavac
command can be used to store formal parameter names and enable the Reflection API to retrieve formal parameter names. - The type rules for equality operators in the Java Language Specification (JLS) Section 15.21 are now correctly enforced by the
javac
command. - The
javac
tool now has support for checking the content ofjavadoc
comments for issues that could lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated whenjavadoc
is run. The feature is enabled by the new-Xdoclint
option. For more details, see the output from running 'javac -X
'. This feature is also available in thejavadoc
tool, and is enabled there by default. - The
javac
tool now provides the ability to generate native headers, as needed. This removes the need to run thejavah
tool as a separate step in the build pipeline. The feature is enabled injavac
by using the new-h
option, which is used to specify a directory in which the header files should be written. Header files will be generated for any class which has either native methods, or constant fields annotated with a new annotation of typejava.lang.annotation.Native
.
- The
javadoc
tool supports the newDocTree
API that enables you to traverse Javadoc comments as abstract syntax trees. - The
javadoc
tool supports the new Javadoc Access API that enables you to invoke the Javadoc tool directly from a Java application, without executing a new process. See the javadoc what's new page for more information. - The
javadoc
tool now has support for checking the content ofjavadoc
comments for issues that could lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated whenjavadoc
is run. The feature is enabled by default, and can also be controlled by the new-Xdoclint
option. For more details, see the output from running 'javadoc -X
'. This feature is also available in thejavac
tool, although it is not enabled by default there.
- 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.SocketPermission
is no longer granted. - The Permissions attribute is required in the JAR file manifest of the main JAR file at all security levels.
- Date-Time Package - a new set of packages that provide a comprehensive date-time model.
- The Rhino javascript engine has been replaced with the Nashorn Javascript Engine
- Pack200 Support for Constant Pool Entries and New Bytecodes Introduced by JSR 292
- JDK8 support for class files changes specified by JSR-292, JSR-308 and JSR-335
- New
SelectorProvider
implementation for Solaris based on the Solaris event port mechanism. To use, run with the system propertyjava.nio.channels.spi.Selector
set to the valuesun.nio.ch.EventPortSelectorProvider
. - 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.
- Parallel Array Sorting
- Standard Encoding and Decoding Base64
- Unsigned Arithmetic Support
- The JDBC-ODBC Bridge has been removed.
- JDBC 4.2 introduces new features.
- Java DB
- JDK 8 includes Java DB 10.10.
- The class
java.net.URLPermission
has been added. - In the class
java.net.HttpURLConnection
, if a security manager is installed, calls that request to open a connection require permission.
- 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.
- Java XML - JAXP
- Hardware intrinsics were added to use Advanced Encryption Standard (AES). The
UseAES
andUseAESIntrinsics
flags are available to enable the hardware-based AES intrinsics for Intel hardware. The hardware must be 2010 or newer Westmere hardware.
Note: AES intrinsics are only supported by the Server VM.
For example, to enable hardware AES, use the following flags:To disable hardware AES use the following flags: - Removal of PermGen.
- Default Methods in the Java Programming Language are supported by the byte code instructions for method invocation.
- JDK 8 includes Java Mission Control 5.3.
Java 8 was released in 18th March 2014, so it’s high time to look into Java 8 Features. In this tutorial, we will look into Java 8 features with examples.
Java 8 Features
Some of the important Java 8 features are;
Let’s have a brief look on these Java 8 features. I will provide some code snippets for better understanding, so if you want to run programs in Java 8, you will have to setup Java 8 environment by following steps.
- 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.
- Download latest Eclipse IDE, it provides support for java 8 now. Make sure your projects build path is using Java 8 library.
Learning Java? Nothing better than a video course trusted by over 1,70,000 students (yes, that many students). Follow this link to get heavy discount on the course.
forEach() method in Iterable interface
Whenever we need to traverse through a Collection, we need to create anIterator
whose whole purpose is to iterate over and then we have business logic in a loop for each of the elements in the Collection. We might get ConcurrentModificationException if iterator is not used properly.Java 8 has introduced forEach method injava.lang.Iterable
interface so that while writing code we focus on business logic only. forEach method takesjava.util.function.Consumer
object as argument, so it helps in having our business logic at a separate location that we can reuse. Let’s see forEach usage with simple example.The number of lines might increase but forEach method helps in having the logic for iteration and business logic at separate place resulting in higher separation of concern and cleaner code.default and static methods in Interfaces
If you read forEach method details carefully, you will notice that it’s defined in Iterable interface but we know that interfaces can’t have method body. From Java 8, interfaces are enhanced to have method with implementation. We can usedefault
andstatic
keyword to create interfaces with method implementation. forEach method implementation in Iterable interface is:We know that Java doesn’t provide multiple inheritance in Classes because it leads to Diamond Problem. So how it will be handled with interfaces now, since interfaces are now similar to abstract classes. The solution is that compiler will throw exception in this scenario and we will have to provide implementation logic in the class implementing the interfaces.Notice that both the interfaces have a common method log() with implementation logic.As you can see thatInterface1
has static method implementation that is used inMyClass.log()
method implementation. Java 8 uses default and static methods heavily in Collection API and default methods are added so that our code remains backward compatible.If any class in the hierarchy has a method with same signature, then default methods become irrelevant. Since any class implementing an interface already has Object as superclass, if we have equals(), hashCode() default methods in interface, it will become irrelevant. Thats why for better clarity, interfaces are not allowed to have Object class default methods.For complete details of interface changes in Java 8, please read Java 8 interface changes.Functional Interfaces and Lambda Expressions
If you notice above interfaces code, you will notice @FunctionalInterface annotation. Functional interfaces are new concept introduced in Java 8. An interface with exactly one abstract method becomes Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. You can think of it like @Override annotation and it’s best practice to use it.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. We can instantiate an interface with anonymous class but the code looks bulky.Since functional interfaces have only one method, lambda expressions can easily provide the method implementation. We just need to provide method arguments and business logic. For example, we can write above implementation using lambda expression as:If you have single statement in method implementation, we don’t need curly braces also. For example above Interface1 anonymous class can be instantiated using lambda as follows:So lambda expressions are means to create anonymous classes of functional interfaces easily. There are no runtime benefits of using lambda expressions, so I will use it cautiously because I don’t mind writing few extra lines of code.A new packagejava.util.function
has been added with bunch of functional interfaces to provide target types for lambda expressions and method references. Lambda expressions are a huge topic, I will write a separate article on that in future.You can read complete tutorial at Java 8 Lambda Expressions Tutorial.Java Stream API for Bulk Data Operations on Collections
A newjava.util.stream
has been added in Java 8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution. This is one of the best feature for me because I work a lot with Collections and usually with Big Data, we need to filter out them based on some conditions.Collection interface has been extended with stream() and parallelStream() default methods to get the Stream for sequential and parallel execution. Let’s see their usage with simple example.If you will run above example code, you will get output like this:Notice that parallel processing values are not in order, so parallel processing will be very helpful while working with huge collections.
Covering everything about Stream API is not possible in this post, you can read everything about Stream API at Java 8 Stream API Example Tutorial.Java Time API
It has always been hard to work with Date, Time and Time Zones in java. There was no standard approach or API in java for date and time in Java. One of the nice addition in Java 8 is thejava.time
package that will streamline the process of working with time in java.Just by looking at Java Time API packages, I can sense that it will be very easy to use. It has some sub-packagesjava.time.format
that provides classes to print and parse dates and times andjava.time.zone
provides support for time-zones and their rules.The new Time API prefers enums over integer constants for months and days of the week. One of the useful class isDateTimeFormatter
for converting datetime objects to strings.For complete tutorial, head over to Java Date Time API Example Tutorial.Collection API improvements
We have already seen forEach() method and Stream API for collections. Some new methods added in Collection API are:Iterator
default methodforEachRemaining(Consumer action)
to perform the given action for each remaining element until all elements have been processed or the action throws an exception.Collection
default methodremoveIf(Predicate filter)
to remove all of the elements of this collection that satisfy the given predicate.Collection
spliterator()
method returning Spliterator instance that can be used to traverse elements sequentially or parallel.- Map
replaceAll()
,compute()
,merge()
methods. - Performance Improvement for HashMap class with Key Collisions
Concurrency API improvements
Some important concurrent API enhancements are:ConcurrentHashMap
compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.CompletableFuture
that may be explicitly completed (setting its value and status).Executors
newWorkStealingPool()
method to create a work-stealing thread pool using all available processors as its target parallelism level.
Java IO improvements
Some IO improvements known to me are:Files.list(Path dir)
that returns a lazily populated Stream, the elements of which are the entries in the directory.Files.lines(Path path)
that reads all lines from a file as a Stream.Files.find()
that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.BufferedReader.lines()
that return a Stream, the elements of which are lines read from this BufferedReader.
Miscellaneous Core API improvements
Some misc API improvements that might come handy are:- ThreadLocal static method withInitial(Supplier supplier) to create instance easily.
- Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order etc.
- min(), max() and sum() methods in Integer, Long and Double wrapper classes.
- logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
- ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file.
- Several utility methods in Math class.
jjs
command is added to invoke Nashorn Engine.jdeps
command is added to analyze class files- JDBC-ODBC Bridge has been removed.
- PermGen memory space has been removed
That’s all for Java 8 features with example programs. If I have missed some important features of Java 8, please let me know through comments.