SlideShare a Scribd company logo
What's New in JAVA 8
Sandeep Kumar Singh
Solution Architect
Agenda
• New Features in Java language
• New Features in Java libraries
• New JAVA Tools
New Features in Java language
• Lambda expression
• Method and Constructor References
• Default Interface method
• Repeating annotations
• Improved Type Inference
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
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
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
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
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.
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
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 { ... }
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
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
New Features in Java libraries
• Optional
• Streams
• Date/Time API
• Nashorn JavaScript engine
• Base64 Encoder/Decoder
• Parallel Arrays
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!
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
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.
Examples (Date/Time API)
Example1 (Clock) :-
final Clock clock = Clock.systemUTC();
System.out.println( clock.instant() ); //2015-08-26T15:19:29.282Z
System.out.println( clock.millis() ); //1397315969360
Example2 (Timezones) :-
System.out.println(ZoneId.getAvailableZoneIds()); //prints all available timezone ids
System.out.println(ZoneId.of("Europe/Berlin").getRules()); // ZoneRules[currentStandardOffset=+01:00]
System.out.println(ZoneId.of("Brazil/East").getRules()); // ZoneRules[currentStandardOffset=-03:00]
Example3 (LocalTime) :-
LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late); // 23:59:59
Example4 (LocalDate) :-
LocalDate independenceDay = LocalDate.of(2015, Month.AUGUST, 15);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek); // SATURDAY
Example5 (LocalDateTime) :-
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek); // WEDNESDAY
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!
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
New JAVA Tools
• Nashorn engine: jjs
• Class dependency analyzer: jdeps
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 !
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
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

More Related Content

PDF
Java 8 - project lambda
DOCX
What are arrays in java script
PPT
JavaScript Arrays
PPTX
Java Language fundamental
PPT
Collections Framework
PPTX
PDF
GUL UC3M - Introduction to functional programming
PDF
The core libraries you always wanted - Google Guava
Java 8 - project lambda
What are arrays in java script
JavaScript Arrays
Java Language fundamental
Collections Framework
GUL UC3M - Introduction to functional programming
The core libraries you always wanted - Google Guava

What's hot (20)

PDF
Google Guava for cleaner code
PDF
Core java pract_sem iii
PDF
Important java programs(collection+file)
PDF
DCN Practical
PDF
Scala vs Java 8 in a Java 8 World
PDF
Advanced Java Practical File
PDF
Google guava - almost everything you need to know
PPTX
Use of Apache Commons and Utilities
PDF
Java Collections API
PDF
Apache Commons - Don\'t re-invent the wheel
PDF
Java 8 Stream API. A different way to process collections.
ODP
JavaScript Web Development
PDF
Google Guava - Core libraries for Java & Android
KEY
Google Guava
PDF
Java programs
DOCX
Java practical
PPTX
Joker 2015 - Валеев Тагир - Что же мы измеряем?
PDF
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
PDF
Python Performance 101
PPTX
What’s new in C# 6
Google Guava for cleaner code
Core java pract_sem iii
Important java programs(collection+file)
DCN Practical
Scala vs Java 8 in a Java 8 World
Advanced Java Practical File
Google guava - almost everything you need to know
Use of Apache Commons and Utilities
Java Collections API
Apache Commons - Don\'t re-invent the wheel
Java 8 Stream API. A different way to process collections.
JavaScript Web Development
Google Guava - Core libraries for Java & Android
Google Guava
Java programs
Java practical
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Python Performance 101
What’s new in C# 6
Ad

Viewers also liked (20)

PDF
Depilat crosshall glo 1
PPTX
Rising Stars Holds Fundraising Golf Outing
PDF
Un prezioso consiglio fv
PDF
Vita first street preview glo
PPTX
Rising Stars Partners with the YMCA to Help Youth Excel in School
PDF
Posizione vita first street
PDF
Brochure ita idc verdiani f
PDF
Depliant idc inglese app
PPTX
Rising Stars’ Meals from the Heart Program
PDF
Crosshall planimetrie
PPTX
δες την ζωη με μια αλλη ματια!
PDF
Vita Crosshall vista posizione
PDF
Foto app vita first street
PDF
Nozioni di base sul diamante
PDF
Brochure glob vita first street
PPTX
Java8.part2
PDF
Daniel Steigerwald - Este.js - konec velkého Schizma
PPTX
Java 8 streams
PDF
Javaz. Functional design in Java 8.
PDF
Pragmatic functional refactoring with java 8
Depilat crosshall glo 1
Rising Stars Holds Fundraising Golf Outing
Un prezioso consiglio fv
Vita first street preview glo
Rising Stars Partners with the YMCA to Help Youth Excel in School
Posizione vita first street
Brochure ita idc verdiani f
Depliant idc inglese app
Rising Stars’ Meals from the Heart Program
Crosshall planimetrie
δες την ζωη με μια αλλη ματια!
Vita Crosshall vista posizione
Foto app vita first street
Nozioni di base sul diamante
Brochure glob vita first street
Java8.part2
Daniel Steigerwald - Este.js - konec velkého Schizma
Java 8 streams
Javaz. Functional design in Java 8.
Pragmatic functional refactoring with java 8
Ad

Similar to What is new in Java 8 (20)

PDF
Java 8 Workshop
PDF
Functional Thinking - Programming with Lambdas in Java 8
PDF
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
PDF
Scala in Places API
PDF
JavaOne 2016 - Learn Lambda and functional programming
PPTX
Anti patterns
PPT
New features and enhancement
PDF
Functional Programming in Java 8 - Lambdas and Streams
PDF
Java7 New Features and Code Examples
PPTX
Pattern Matching in Java 14
PDF
Productive Programming in Java 8 - with Lambdas and Streams
PDF
Java 8 Lambda Expressions
PDF
Scala - en bedre og mere effektiv Java?
PPTX
Java fundamentals
PDF
Java 5 and 6 New Features
PDF
Solr @ Etsy - Apache Lucene Eurocon
PDF
Alternate JVM Languages
PPTX
New Features in JDK 8
PDF
FP in Java - Project Lambda and beyond
PPTX
Java 8 Workshop
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Scala in Places API
JavaOne 2016 - Learn Lambda and functional programming
Anti patterns
New features and enhancement
Functional Programming in Java 8 - Lambdas and Streams
Java7 New Features and Code Examples
Pattern Matching in Java 14
Productive Programming in Java 8 - with Lambdas and Streams
Java 8 Lambda Expressions
Scala - en bedre og mere effektiv Java?
Java fundamentals
Java 5 and 6 New Features
Solr @ Etsy - Apache Lucene Eurocon
Alternate JVM Languages
New Features in JDK 8
FP in Java - Project Lambda and beyond

Recently uploaded (20)

PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
DOCX
The Five Best AI Cover Tools in 2025.docx
PDF
medical staffing services at VALiNTRY
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
ai tools demonstartion for schools and inter college
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Digital Strategies for Manufacturing Companies
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Transform Your Business with a Software ERP System
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Odoo POS Development Services by CandidRoot Solutions
Upgrade and Innovation Strategies for SAP ERP Customers
Become an Agentblazer Champion Challenge Kickoff
Which alternative to Crystal Reports is best for small or large businesses.pdf
The Five Best AI Cover Tools in 2025.docx
medical staffing services at VALiNTRY
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
ai tools demonstartion for schools and inter college
ManageIQ - Sprint 268 Review - Slide Deck
Online Work Permit System for Fast Permit Processing
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Digital Strategies for Manufacturing Companies
How to Migrate SBCGlobal Email to Yahoo Easily
Softaken Excel to vCard Converter Software.pdf
A REACT POMODORO TIMER WEB APPLICATION.pdf
L1 - Introduction to python Backend.pptx
Transform Your Business with a Software ERP System
ISO 45001 Occupational Health and Safety Management System
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus

What is new in Java 8

  • 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.
  • 17. Examples (Date/Time API) Example1 (Clock) :- final Clock clock = Clock.systemUTC(); System.out.println( clock.instant() ); //2015-08-26T15:19:29.282Z System.out.println( clock.millis() ); //1397315969360 Example2 (Timezones) :- System.out.println(ZoneId.getAvailableZoneIds()); //prints all available timezone ids System.out.println(ZoneId.of("Europe/Berlin").getRules()); // ZoneRules[currentStandardOffset=+01:00] System.out.println(ZoneId.of("Brazil/East").getRules()); // ZoneRules[currentStandardOffset=-03:00] Example3 (LocalTime) :- LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); // 23:59:59 Example4 (LocalDate) :- LocalDate independenceDay = LocalDate.of(2015, Month.AUGUST, 15); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); // SATURDAY Example5 (LocalDateTime) :- LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY
  • 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