Wednesday 18 November 2015

New features in Java 8

Java 8 included following new Features.

    1. Lambda expressions
    2. Method references
    3. Default Methods (Defender methods)
    4. A new Stream API (Parallel operations)
    5. Optional Class
    6. A new Date/Time API
    7. Nashorn, the new JavaScript engine (Java + JavaScript)
    8. Removal of the Permanent Generation
    9. Other New Features

1. Lambda Expressions

The biggest new feature of Java 8 is language level support for lambda expressions (Project Lambda). Java lambda expressions are Java's first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand.

Following are the important characteristics of a lambda expression

    • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
    • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
    • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
    • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

syntax: 

parameter -> expression body

Examples:


1. With type declaration

MathOperation addition = (int a, int b) -> a + b;  

2. With out type declaration

MathOperation subtraction = (a, b) -> a - b;  

3. With return statement along with curly braces

MathOperation multiplication = (int a, int b) -> { return a * b; };  
4. Without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;


More Info

2. Method references(Parallel operations)


You use lambda expressions to create anonymous methods. Method references help to point to methods by their names. A method reference is described using :: (double colon) symbol.
You can use replace Lambda Expressions with Method References where Lamdba is invoking already defined methods.
You can’t pass arguments to methods Reference

There are four kinds of method references:

  1. Reference to a static method  ContainingClass::staticMethodName
  2. Reference to an instance method of a particular object
    containingObject::instanceMethodName
  3. Reference to an instance method of an arbitrary object of a particular type
    ContainingType::methodName
  4. Reference to a constructor ClassName::new

Example:

List names = new ArrayList();

names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");


names.forEach(System.out::println);


More Info

3. Default Methods (Defender methods)

Default methods can be provided to an interface without affecting implementing classes as it includes an implementation just by adding the keyword default before the method’s access modifier.
Modify one interface in JDK framework breaks all classes that extends the interface. Default methods enable us to add new or default functionalities/behavior to existing interfaces without breaking the classes that implements that interface.
After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8.

Example:


public interface vehicle {

  default void print(){

 System.out.println("I am a vehicle!");

  }

}
4. A new Stream API.
Don't confuse with InputStream and OutputStream from Java I/O. This is Completely different thing. Streams adhere to a common Pipes and Filters software pattern.

A Stream is a free flowing sequence of elements. They do not hold any storage as that responsibility lies with collections such as arrays, lists and sets. Every stream starts with a source of data, sets up a pipeline, processes the elements through a pipeline and finishes with a terminal operation. They allow us to parallelize the load that comes with heavy operations without having to write any parallel code. A new package java.util.stream was introduced in Java 8 to deal with this feature.

Example:

List<String>  myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

Deeper Look at Streams

The Stream interface is defined in java.util.stream package. Starting from Java 8, the java collections will start having methods that return Stream. This is possible because of another cool feature of Java 8, which is default methods. Streams can be defiled as a sequence of elements from a source that supports aggregate operations.
The source here refers to a Collection, IO Operation or Arrays who provides data to a Stream. Stream keeps the order of the data as it is in the source. Just like functional programming languages, Streams support Aggregate Operations. The common aggregate operations are filter, map, reduce, find, match, sort. These operations can be executed in series or in parallel.

The Streams also support Pipelining and Internal Iterations. The Java 8 Streams are designed in such a way that most of its stream operations returns Streams only. This help us creating chain of various stream operations. This is called as pipelining. The pipelined operations looks similar to a sql query.


5. Optional Class


Optional is a new container type that wraps a single value, if the value is available. So it's meant to convey the meaning that the value might be absent. 

Optional is an attempt to reduce the number of null pointer exceptions in Java systems, by adding the possibility to build more expressive APIs that account for the possibility that sometimes return values are missing. By using Optional, and never working with null, you could avoid null checks altogether.

Example:


public Optional<String> getOptionalNullString(){

 return(null);

}

java.util.Optional is a container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

More Info


6. A new Date/Time API

Working with New Date and Time objects


By default LocalDate/Time classes will use the system clock in the default time zone. We can change this by providing a time zone or an alternative Clock implementation.


They are also coming with better time zone support with ZoneOffSet, ZoneId, ZonedDateTime or OffsetDateTime. 
Parsing and Formatting of Dates are also revamped with new DateTimeFormatter class.
Clock, which can be used to get current instant, date and time using time zone.

Deeper Look at Date/Time API

New date and time API is located inside java.time package and some of the key classes are following.
Instant - Represents a timestamp
LocalDate - Represents a year-month-day date without time.
LocalTime - Represents a time without dates.
LocalDateTime - Combines date and time in one class.
We can use the plus and minus methods to add or subtract specific amounts of time. Note that these methods always return a new instance (Java 8 date/time classes are immutable).

Example:

LocalDate tomorrow = LocalDate.now().plusDays(1);
Some information can be obtained without providing a specific date. For example, we can use the Year class if we need information about a specific year:

Example:

Year currentYear = Year.now();
  boolean isLeap = currentYear.isLeap();
Timestamps
  Classes like LocalDate and ZonedDateTime provide a human view on time. However, often we need to work with time viewed from a machine perspective. For this we can use the Instant class which represents timestamps. 

Example:

  Instant now = Instant.now(); // current time
  Instant fromUnixTimestamp = Instant.ofEpochSecond(1262347200); // from unix timestamp, 2010-01-01 12:00:00
  Instant fromEpochMilli = Instant.ofEpochMilli(1262347200000l); // same time in millis 
Periods and Durations
  Period and Duration are two other important classes. Like the names suggest they represent a quantity or amount of time. A Period uses date based values (years, months, days) while a Duration uses seconds or nanoseconds to define an amount of time.

Example:

  LocalDate firstDate = LocalDate.of(2010, 5, 17); // 2010-05-17
  LocalDate secondDate = LocalDate.of(2015, 3, 7); // 2015-03-07
  Period period = Period.between(firstDate, secondDate);

  Instant firstInstant= Instant.ofEpochSecond( 1294881180 ); // 2011-01-13 01:13
  Instant secondInstant = Instant.ofEpochSecond(1294708260);
  Duration between = Duration.between(firstInstant, secondInstant);
More Info 
More Examples

7. Nashorn, the new JavaScript engine (Java + JavaScript)


Nashorn is a JavaScript engine for the JVM that is released with Java 8. It has replaced the existing Rhino engine.



As JavaScript is getting popular on server-side programming (like Node.js).

The Nashorn javascript engine can either be used pragmatically from java programs or by utilizing the command line tool jjs, which is located in $JAVA_HOME/bin. If you plan to work with jjs you might want to put a symbolic link for simple access:

Example 1:


$  jjs -scripting heredocs.js

Example 2:

ScriptEngineManager engineManager =  new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval(new FileReader("src/sample2/mustache.js"));
engine.eval("print('Hello World!');");

8. Removal of the Permanent Generation

Permanent Generation memory space is completely removed.
The good news is that it means no more java.lang.OutOfMemoryError: PermGen space problems and no need for you to tune and monitor this memory space any more.

Impact:

The PermSize and MaxPermSize JVM arguments are ignored and a warning is issued if present at start-up.
Metaspace: A new memory space is born.
More Info

9. Other New Features

Concurrent accumulators

One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads.

Parallel operations

You can think of this as an extension of iterators where the actual operation of extracting the next item from a collection on which to operate is carried out by an iterator. An exciting possibility opened by this design pattern is to enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework. 

String.join

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

Type Annotations

List<@Nullable String>
@NotNull String[] arr;
new @NonEmpty @Readonly List(myNonEmptyStringSet)
new @Interned MyObject()

Functional Interfaces

java.util.function

Stamped Locks

The problem is that the ReadWriteLock can be super slow (up to 10x), which kind of defeats its purpose. Java 8 introduces a new ReadWrite lock – called StampedLock.

Controlling OS Processes

Launching an OS process from within your code is right there with JNI calls – it’s something you do half-knowing there’s a good chance you’re going to get some unexpected results and some really bad exceptions down the line.

Exact Numeric Operations

Math class geared towards protecting sensitive code from implicit overflows, by throwing an unchecked ArithmeticException when the value of an operation overflows its precision.
int safeC = Math.multiplyExact(bigA, bigB); // will throw ArithmeticException if result exceeds +-2^31

Secure Random Generation

Java 8 has added a new method called SecureRandom.getInstanceStrong() whose aim is to have the JVM choose a secure provider for you.

References


Other Milestones Completed
New Features in Java SE 8 PPT
8 Great Java 8 Features
Video: New Features in Java SE 8
JDK 8 Features

No comments:

Post a Comment