Introduction
This article is a light introduction to the Java Platform, Standard Edition 8 (Java SE 8 ) and JDK 8. After Java 5 (released in 2004), Java brings hundreds of new features to Java as a language, its compiler, tools, libraries and the JVM itself. After reading this article, you should have a basic knowledge of the new features. If you aren't familiar with the Java language, it might be hard to understand some points.
1) Lambda Expressions
Lambda Expressions is one of the biggest new feature at the language level support in Java 8. Simply it is a method without declaration, like access modifier, declaration, return value and name. It enable us to treat functionality as a method argument, or code as data. In other words it allows us to write a method in the same place where we will use it. A Lambda Expression is useful when a method is being used only once. The syntax to create a Lambda Expression is:
Syntax: arguments -> body.
Example: myString -> System.out.println(myString).
It contains parentheses, an arrow token and a body (single expression or statement of block). It has an input argument, a body and an optional return value like a normal Java method.
- import java.io.*;
- import java.util.*;
- import java.util.function.Predicate;
- public class lambda_demo
- {
- public static void main(String [] a)
- {
- List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
- System.out.println("List Contain");
- evaluate(list, (n)->true);
- System.out.println("Even Numbers are:");
- evaluate(list, (n)-> n%2 == 0 );
- System.out.println("Odd Numbers are:");
- evaluate(list, (n)-> n%2 == 1 );
- System.out.println("Numbers smaller than 3 are:");
- evaluate(list, (n)-> n < 5 );
- System.out.println("Numbers greater than 3 are:");
- evaluate(list, (n)-> n > 5 );
- }
- public static void evaluate(List<Integer> list, Predicate<Integer> predicate)
- {
- for(Integer n: list)
- {
- if(predicate.test(n))
- {
- System.out.println(n + " ");
- }
- }
- }
- }
Output
2) Method Reference
The other important feature in Java 8 is Method Reference that provides a way to use a method without executing it. Simply if we already have a method name, we can easily read something.
There are the following four types of Method Reference:
- Reference to a static method.
- Reference to an instance method of a specific object.
- Reference to an instance method of an arbitrary object of a specific type.
- Reference to a constructor.
Let's take an example:
- import java.util.function.Supplier;
- public class MRDemo
- {
- public static void main(String[] args)
- {
- String s = "Example of method references ";
- print(s::toString);
- print(() -> s.toString());
- print(new Supplier<String>()
- {
- public String get()
- {
- return s.toString();
- }
- });
- }
- public static void print(Supplier<String> supplier)
- {
- System.out.println(supplier.get());
- }
- }
Output
3) Streams
It is located in the "java.util.stream" pakage. This feature is added to the Java Collections API. In this the process of collecting an object is done in a different way. Because it does not store data, a Collection or Array is the source of the data to the stream. It is like an iterator that allows a single run over the collection. It supports the map, filter, reduce pattern and executes lazily. It can run sequentially or in parallel depending on requirements.
We can do a Core stream operation using the following methods:
- filter(),
- map(),
- sorted(),
- forEach(),
- collect(),
- match(),
- count(),
- reduce().
Some of the examples of implementing it
Using "Stream.of":
- import java.util.stream.*;
- public class sd1
- {
- public static void main(String[] args)
- {
- Stream<Integer> stream = Stream.of(1,2,3,4,5);
- stream.forEach(s -> System.out.println(s));
- }
- }
Output
And:
- import java.util.stream.*;
- public class sd2
- {
- public static void main(String[] args)
- {
- Stream<Integer> stream = Stream.of( new Integer[]{1,2,3,4,5} );
- stream.forEach(s -> System.out.println(s));
- }
- }
Output
Using "stream.genrate":
- import java.util.stream.*;
- import java.util.*;
- public class sd3
- {
- public static void main(String[] args)
- {
- Stream<Date> stream = Stream.generate(() -> { return new Date();});
- stream.forEach(s -> System.out.println(s));
-
- }
- }
4) Compact Profiles
Another useful feature of Java 8 is Compact Profile. In Compact Profile, the applications that do not require the entire Java platform reduces the use of the memory footprint or we can say that it allows us to deploy only those components that are required by the application. The Java SE 8 compiler (javac) allows the application to be compiled using one of the new supported features called "-profile".
There are 3 types of compact profiles named Compact1, Compact2 and Compact3. And the next one is the Superset of the last one, in other words Compact3 is a superset of Compact2 and correspondingly Compact 2 is the superset of Compact1.
Compact 1 |
Compact 2 |
Compact 3 |
Core |
JDBC |
Security |
Security |
RMI |
JMX |
Serialization |
XML JAXP |
JNDI |
Networking |
|
XML JAXP |
Ref Objects |
|
Management |
Regular Expressions |
|
Instrumentation |
Date and Time |
|
|
Input/Output |
|
|
Collections |
|
|
Logging |
|
|
Concurrency |
|
|
Reflection |
|
|
JAR |
|
|
ZIP |
|
|
Versioning |
|
|
Internationalization |
|
|
JNI |
|
|
Overriden Mechanism |
|
|
Extension Mechanism |
|
|
Scripting |
|
|
Using the jdeps Tool
Method Name |
Description |
-s |
Print dependency summary. |
-v |
Print additional info. |
-V <level> |
Print package-level or class-level dependencies. |
-c <path> |
Specify where to find class file. |
-p <pkg name> |
Restrict analysis to classes matching pattern. |
-e <regex> |
Restrict analysis to packages matching pattern. |
-P |
Show profile or the file containing a package. |
-R |
Version information. |
Example
- class helloworld
- {
- public static void main(String args[])
- {
- System.out.println("Hello World");
- }
- }
Output: jdps -P helloworld.class
5) Optional
One of the amazing features of Java 8 is Optional that is present in the util package. Using the "java.util.optional" class we can deal with null pointer exceptions or we can say that we can make our code more readable then before and can protect our code from null pointer exceptions. According to my view, it is very confusing to use Optional in the starting period.
Let's use an example of null pointer exception: This program throws null pointer exceptions.
- import java.util.*;
- public class opt_demo
- {
- public String getNullString()
- {
- return(null);
- }
- public static void main(String[] args)
- {
- opt_demo obj=new opt_demo();
- String nullString=obj.getNullString();
- System.out.println(nullString);
- }
- }
Output
So, here is the solution with the use of optional: Here Optional is used.
- import java.util.Optional;
- public class opt_test
- {
- public Optional<String> getOptionalNullString()
- {
- return(null);
- }
- public static void main(String[] args)
- {
- opt_test obj=new opt_test();
- Optional<String> optionalString=obj.getOptionalNullString();
- System.out.println(optionalString);
- }
- }
Output
Some methods of Optional
Method Name |
Uses |
Work |
empty |
public static <T>Optional<T>empty() |
Returns an empty Optional instance |
of |
public static <T>Optional<T>of(T value) |
Returns specified non-null value |
ofNullable |
public static <T>Optional<T>ofNullable(T value) |
Returns specified value, otherwise returns an empty optional |
filter |
public Optional<T>filter(Predicate<? super T>predicate) |
If value is present and matches, return value describing Optional, else returns an empty optional |
map |
public <U>Optional<U>map(function<? super T,? estends U>mapper) |
If present, apply given mapping function and if non-null, return result describing Optional, else returns an empty optional |
flatMap |
public <U>Optional<U>flatMap(function<? super T,Optional< U>>mapper) |
It is similar to map() method, but flatMap doesn't bind it with an additional Optional |
6) New Date/Time API(JSR 310)
In Java SE 8, another feature that was introduced is the Date/Time package, "java.time" and it was developed under JSR 310(API) that provides us a extensive model for Date and Time. It contains all the classes for date/time, time zones, duration, instants and clock manipulation. It is based on the ISO calendar system that is commonly used for global calenders. Some of its class is described below:
Class |
Description |
LocalDate |
Shows only a date (without offset or zone) |
LocalTime |
Shows only time (without offset or zone) |
LocalDateTime |
Shows date and time (without offset or zone) |
OffsetDate |
Shows a date with an offset such as +05:30 |
OffsetTime |
Shows time with an offset such as +05:30 |
OffsetDateTime |
Shows date and time with an offset such as +05:30 |
ZonedDateTime |
Shows date and time with offset and time zone |
YearMonth |
Shows a year and month |
MonthDay |
Shows month and day |
Period |
Shows a defined time (such as 1 week) |
Example
- import java.time.*;
- import java.time.format.DateTimeFormatter;
- public class date_time
- {
- public static void main(String[] args)
- {
- System.out.println("");
-
- LocalDate today = LocalDate.now();
- System.out.println("Current Date="+today);
-
- LocalDate firstDay_2015 = LocalDate.of(2015, Month.JANUARY, 1);
- System.out.println("Specific Date="+firstDay_2015);
-
- LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
- System.out.println("Current Date in IST="+todayKolkata);
- System.out.println("");
-
- LocalTime time = LocalTime.now();
- System.out.println("Current Time="+time);
-
- LocalTime specificTime = LocalTime.of(12,20,25,40);
- System.out.println("Specific Time of Day="+specificTime);
-
- LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
- System.out.println("Current Time in IST="+timeKolkata);
- System.out.println("");
-
- LocalDate date = LocalDate.now();
-
- System.out.println("Default format of LocalDate="+date);
-
- System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
- System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));
- System.out.println("");
- LocalDateTime dateTime = LocalDateTime.now();
-
- System.out.println("Default format of LocalDateTime="+dateTime);
-
- System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
- System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
- }
- }
Output
7) Nashorn JavaScript Engine
Java SE 8 introduced another interesting feature, Nashrorn (pronounced "nass-horn"). Nashrorn is a German word for Rhinoceros. JavaScript Engine. For the Java Virtual Machine (JVM) Nashrorn replaces Rhino as the default JavaScript Engine. We can implement it in two ways, one way is to use it programmatically in a Java program and second, using the jjs command line (used for learning purposes) tool located in $JAVA_HOME/bin.
The following are some ways to implement the Nashron JavaScript Engine:
- JavaScript Functions from Java
- Java Methods from JavaScripts
- ScriptObjectMirror
- Language Extensions
A simple example of "jjs" using the command line
Output
Now, using Nashorn embedded with Java :
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class nash_js
- {
- public static void main(String[] args) throws Exception
- {
- ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
- ScriptEngine scriptEngine = scriptEngineManager
- .getEngineByName("nashorn");
- try
- {
- scriptEngine.eval("print('Example of Nashorn embedded in java!');");
- }
- catch (final ScriptException se)
- {
- se.printStackTrace();
- }
- }
- }
Output
Summary
The summarized version of the preceding article is that Java SE 8 introduced many features for making Java more productive than ever before and the entire credit goes to Oracle's implementations. Features like Lambda Expressions, Method References, Streams, Compact Profile, the Optional (JSR 310) API and the Nashorn JavaScript Engine are some very useful features. By using a "lambda expression" we can code in the same place where we will use it. Using a "method reference" we can use a method without executing it. Using "Streams" we can process a collection of objects in a different way. Using "compact profile" we can run only the code that is required by the Java environment. Using "optional" we can handle null pointer exceptions. Using the "date/time API" we can get dates/times in many ways and formats. Using the "Nashorn JavaScript Engine" we can run JavaScript embedded into Java code.