1. What's New in JAVA 8
Sandeep Kumar Singh
Solution Architect
2. Agenda
• New Features in Java language
• New Features in Java libraries
• New JAVA Tools
3. New Features in Java language
• Lambda expression
• Method and Constructor References
• Default Interface method
• Repeating annotations
• Improved Type Inference
4. Lambda expression
• Enable to treat functionality as a method
argument, or code as data.
• Lambda expressions express instances of
single-method interfaces (referred to as
functional interfaces) more compactly
5. Examples
List<String> strList = Arrays.asList("peter", "anna",
"mike", "xenia");
for(String name : strList){
System.out.println(name);
}
Arrays.asList( "peter", "anna", "mike", "xenia"
).forEach( e -> System.out.println( e ) );
List<String> names = Arrays.asList("peter", "anna",
"mike", "xenia");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
Collections.sort(names, (a, b) ->
b.compareTo(a));
JAVA 7
JAVA 7
JAVA 8
JAVA 8
6. Method and Constructor References
• Provides the useful syntax to refer directly to
exiting methods or constructors of Java classes
or objects.
• Java 8 enables you to pass references of
methods or constructors via the :: keyword
7. Examples (Method and Constructor References)
class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public static int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
// Reference to an instance method
ComparisonProvider myComparisonProvider = new
ComparisonProvider();
Arrays.sort(rosterAsArray,
myComparisonProvider::compareByName);
// Reference to a static method
Arrays.sort(rosterAsArray, ComparisonProvider
::compareByName);
class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
interface PersonFactory<P extends Person> {
P create(String firstName, String lastName);
}
PersonFactory<Person> personFactory =
Person::new;
Person person = personFactory.create("Peter",
"Parker");
Method References Constructor References
8. Default Interface method
• Enable to add new functionality to an
interface by utilizing the “default” keyword.
• This is different from abstract methods as they
do not have a method implementation
• This ensures binary compatibility with code
written for older versions of those interfaces.
9. Examples (Default Interface method)
interface Formula {
double calculate(int a);
default double sqrt(int a) {
return Math.sqrt(a);
}
}
Formula formula = new Formula() {
@Override
public double calculate(int a) {
return sqrt(a * 10);
}
};
formula.calculate(10); // 10.0
formula.sqrt(4); //2
10. Repeating annotations
• Repeating Annotations provide the ability to
apply the same annotation type more than
once to the same declaration or type use.
@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }
@Alert(role="Manager")
@Alert(role="Administrator")
public class UnauthorizedAccessException extends
SecurityException { ... }
11. Improved Type Inference
• The Java compiler takes advantage of target
typing to infer the type parameters of a
generic method invocation.
• The target type of an expression is the data
type that the Java compiler expects depending
on where the expression appears
12. Examples (Improved Type Inference)
class Value< T > {
public static< T > T defaultValue() {
return null;
}
public T getOrDefault( T value, T defaultValue )
{
return ( value != null ) ? value : defaultValue;
}
}
public class TypeInference {
public static void main(String[] args) {
final Value< String > value = new Value<>();
value.getOrDefault( "22",
Value.<String>defaultValue() );
}
}
public class Value< T > {
public static< T > T defaultValue() {
return null;
}
public T getOrDefault( T value, T defaultValue
) {
return ( value != null ) ? value : defaultValue;
}
}
public class TypeInference {
public static void main(String[] args) {
final Value< String > value = new Value<>();
value.getOrDefault( "22",
Value.defaultValue() );
}
}
JAVA 7 JAVA 8
13. New Features in Java libraries
• Optional
• Streams
• Date/Time API
• Nashorn JavaScript engine
• Base64 Encoder/Decoder
• Parallel Arrays
14. Optional (a solution to NullPointerExceptions)
• Optional is a simple container for a value
which may be null or non-null.
• It provides a lot of useful methods so the
explicit null checks have no excuse anymore.
Example 1 :-
Optional<String> optional = Optional.of("bam");
optional.isPresent(); // true
optional.get(); // "bam"
optional.orElse("fallback"); // "bam”
optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b“
Example 2 :-
Optional< String > fullName = Optional.ofNullable( null );
System.out.println( "Full Name is set? " + fullName.isPresent() ); //Full Name is set? false
System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) ); // Full Name: [none]
System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) ); //Hey Stranger!
15. Streams
• Stream API is integrated into the Collections
API, which enables bulk operations on
collections, such as sequential or parallel map-
reduce transformations.
int max = 1000000;
List<String> values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
UUID uuid = UUID.randomUUID();
values.add(uuid.toString());
}
Example 1 (Sequential Sort):-
long count = values.stream().sorted().count();
System.out.println(count); // sequential sort took: 899 ms
Example 2 (Parallel Sort) :-
long count = values.parallelStream().sorted().count();
System.out.println(count); // parallel sort took: 472 ms
16. Date/Time API
• The Date-Time package, java.time, introduced in
the Java SE 8 release
• Provides a comprehensive model for date and
time and was developed under JSR 310: Date
and Time API.
• Although java.time is based on the International
Organization for Standardization (ISO) calendar
system, commonly used global calendars are
also supported.
18. Base64 Encoder/Decoder
• Support of Base64 encoding has made its way
into Java standard library with Java 8 release.
final String text = "Base64 finally in Java 8!";
final String encoded = Base64.getEncoder() .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded ); // QmFzZTY0IGZpbmFsbHkgaW4gSmF2YSA4IQ==
final String decoded = new String( Base64.getDecoder().decode( encoded ), StandardCharsets.UTF_8 );
System.out.println( decoded ); // Base64 finally in Java 8!
19. Parallel Arrays
• Java 8 release adds a lot of new methods to
allow parallel arrays processing
long[] arrayOfLong = new long [ 20000 ];
Arrays.parallelSetAll( arrayOfLong, index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
Arrays.stream( arrayOfLong ).limit( 10 ).forEach( i -> System.out.print( i + " " ) );
System.out.println();
// 591217 891976 443951 424479 766825 351964 242997 642839 119108 552378
Arrays.parallelSort( arrayOfLong );
Arrays.stream( arrayOfLong ).limit( 10 ).forEach( i -> System.out.print( i + " " ) );
System.out.println();
//39 220 263 268 325 607 655 678 723 793
20. New JAVA Tools
• Nashorn engine: jjs
• Class dependency analyzer: jdeps
21. Nashorn engine: jjs
• jjs is a command line based standalone
Nashorn engine.
• It accepts a list of JavaScript source code files
as arguments and runs them.
Create a file func.js with following content:
function f() {
return “Hello ”;
};
print( f() + “World !” );
To execute this fie from command, let us pass it as an argument to jjs:
jjs func.js
The output on the console will be:
Hello World !
22. Class dependency analyzer: jdeps
• Provide a command-line tool in the JDK so that
developers can understand the static dependencies
of their applications and libraries.
jdeps org.springframework.core-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar -> C:Program FilesJavajdk1.8.0jrelibrt.jar
org.springframework.core (org.springframework.core-3.0.5.RELEASE.jar)
-> java.io
-> java.lang
-> java.lang.annotation
-> java.lang.ref
-> java.lang.reflect
-> java.util
-> java.util.concurrent
-> org.apache.commons.logging not found
-> org.springframework.asm not found
-> org.springframework.asm.commons not found
org.springframework.core.annotation (org.springframework.core-3.0.5.RELEASE.jar)
-> java.lang
-> java.lang.annotation
-> java.lang.reflect
-> java.util
23. Java 9 Proposed Feature List
• Project Jigsaw – Modular Source Code
• Process API Updates
• Light Weight JSON API
• Money and Currency API
• Improved Contended Locking
• Segmented Code Cache
• Smart Java Compilation – Phase Two