Contents

A Quick Guide To All New Features On Java-8

/java8-quick-guide-to-all-new-features/thumbnail.png
Java-8 New Features

Java 8 or also known as JDK 8 or Java 1.8 - was initially released in March 18, 2014. It came with lots of interesting features and was organized in terms of JDK Enhancement Proposals (JEPs).

Interesting features

  • Lambda expressions
  • Streams
  • Optional
  • Java Date and Time API
  • Concurrency Enhancements
  • Java Nashorn JavaScript

1. Lambda Expression

Addition of lambda expressions (closures) and its supporting features,
Includes - method references, enhanced type inference, and virtual extension methods.

1
2
List<Integer> list = Arrays.asList(0, 1, 2);
list.forEach((n) -> System.out.println(n));

Using method reference

1
list.forEach(System.out::println);

For more See

2. Streams

Addition of functionality to the Java Collections Framework for bulk operations upon data. This is commonly referenced as filter/map/reduce for Java.” The bulk data operations include both serial (on the calling thread) and parallel (using many threads) versions of the operations.

1
2
3
4
5
6
7
8
9
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);

As you can see, operations upon data are generally expressed as lambda functions.

For more See

3. Optional

Optional was introduced to prevent NullPointerException. It is a container object which may or may not contain a non-null value.
If a value is present i.e not null, than isPresent() will return true and calling get() will return the value.

1
2
3
4
5
6
7
8
String name = "java8Optional";
Optional<String> strName = Optional.of(name);

strName.isPresent();           // true
strName.get();                 // returns "java8Optional"

// Or also we can provide default
String val = strName.orElse("fallback value if name is null");    

4. New Date and Time API

Prior to Java 8 - packages ( util.Date, util.Calendar, util.TimeZone ) were Not type safe and were mutable - hence could not be used in multithreading.
Java-8 introduces, New Java.time package:

  • Clock
  • Instant
  • LocalDate, LocalDateTime, Year, YearMonth (ISO 8601)
  • ZonedDateTime, OffsetDateTime, OffsetTime

It means API under the package java.time. Now provides:

  • Support standard time concepts including date, time, instant, and time-zone
  • Partial, duration, period, and intervals
  • Immutable implementations, Integrate with existing JDK APIs
  • Use relevant standards, including ISO-8601, CLDR, and BCP47
  • Be based on an explicit time-scale with a connection to UTC
  • DateTimeFormatter for converting DateTime to string and vice versa.

Some code sample:

1
2
3
4
5
6
Clock clock = Clock.systemDefaultZone();
LocalDate today = LocalDate.now();
LocalDate.of(2019, Month.APRIL, 16).getDayOdWeek(); 

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsed = LocalDateTime.parse("2019-01-03T16:01:00.062", formatter);

5. Concurrency Enhancements

Asynchronous task chaining with CompletableFuture. The Future makes use of result of asynchronous task and monitor its progress from outside, using method of Future interface.
The Java-8 new interface and concurrent classes further enhance this concept.

1
2
interface CompletableFuture<T>.AsynchronousCompletionTask
interface CompletionStage<T>

// … for more see javadocs

The CompletableFuture allows creation and execution of chains of asynchronous tasks, and allows us to automatically process the results of each task upon completion.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Supplier<Integer> task1 = (...) -> {
   ...                                   // some complex calculation
   return 1;                             // example result
};

Supplier<Integer> task2 = (...) -> {
   ...                                   // some complex calculation
   throw new RuntimeException();         // example exception
};

Supplier<Integer> task3 = (...) -> {
   ...                                   // some complex calculation 
   return 3;                             // example result
};

supplyAsync(task1)     // run task1
       .applyToEither(                   // use whichever result is ready first, result of task1 or
               supplyAsync(task2),       // result of task2
               (Integer i) -> i)         // return result as-is
       .thenCombine(                     // combine result
               supplyAsync(task3),       // with result of task3
               Integer::sum)             // using summation
       .thenAccept(System.out::println); // print final result after execution

And more enhancements

  • Scalable update variables – DoubleAccumulator, DoubleAdder, etc
  • ConcurrentHashMap updates – improved scanning support, key computation
  • ForkJoinPool improvements – Completion based design for IO bound applications–Thread that is blocked hands work to thread that is running

To understand complete concepts on Java Concurrency See

6. Nashorn Javascript Engine

Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs which is used to execute JavaScript code. ECMAScript-262 Edition 5.1

7. New command-line tool, jjs

1
2
$ jjs
jjs> print('Hello’);

You can also execute .js file from the Java code

1
2
3
4
5
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

engine.eval("print('Hello');");
// executing .js file
engine.eval(new FileReader("demotest.js"));


Similary other enhancements includes

8. Default methods

For providing default method implemention.

1
2
3
4
5
6
interface Collection<T> {
   ...
   Default Stream<T> stream(){
      ...
   }
}

9. Method References

Shorthand syntax for a lambda expression that executes just ONE method.

1
2
3
list.replaceAll(s -> s.toUpperCase());
// method reference
list.replaceAll(String::toUpperCase);

10. Encoding and Decoding (Base64)

Java8 also contains class java.util.Base64 for Base64 encryption and decryption. The supported alphabet is specified by Java in RFC 4648 and RFC 2045.

11. StringJoiner:

StringJoiner is used to construct a sequence of characters separated by a delimiter. like comma( , ), hyphen( - ).

1
2
3
4
5
6
7
StringJoiner strJoiner = new StringJoiner(",");   

// Adding values to StringJoiner  
strJoiner.add("One");          
strJoiner.add("Two");                  
System.out.println(strJoiner);  
// One,Two

12. Annotation on Java Types:

Pluggable type checkers can be added to parameters, can only be used on type declarations; Classes, methods, variable definitions.

1
public void process(@notnull List data) {...}

13. Internationalization Enhancements

  • generate locale data files, CLDR support, Locale Mapping.

14. Security

  • Better implementation of SecureRandom number generator
  • Enhanced Certificate Revocation-Checking API
  • HTTP URL Permissions
  • Other several security patches and improvements

15. Remove the permanent generation:

  • No more need to tune the size of it
  • Current objects moved to Java heap or native memory
  • Interned strings, Class metadata, Class static variables
  • Part of the HotSpot, JRockit convergence

16. Access to parameter names at runtime:

Retrieve parameter names of methods and constructors– At run-time via core reflection.

JavaFX Applications - Support the direct launching of JavaFX applications.
And Much more… Check JEPS Documentation