SlideShare a Scribd company logo
i
AbouttheTutorial
Java 8 is the most awaited and is a major feature release of Java programming language.
This is an introductory tutorial that explains the basic-to-advanced features of Java 8 and
their usage in a simple and intuitive way.
Audience
This tutorial will be useful for most Java developers, starting from beginners to experts.
After completing this tutorial, you will find yourself at a moderate level of expertise in Java
8, from where you can take yourself to next levels.
Prerequisites
Knowledge of basic Java programming language is the only prerequisite for learning the
concepts explained in this tutorial.
Copyright&Disclaimer
 Copyright 2015 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
ii
TableofContents
About the Tutorial....................................................................................................................................i
Audience..................................................................................................................................................i
Prerequisites............................................................................................................................................i
Copyright & Disclaimer.............................................................................................................................i
Table of Contents....................................................................................................................................ii
1. JAVA 8 ─ OVERVIEW ............................................................................................................1
New Features..........................................................................................................................................1
2. JAVA 8 ─ ENVIRONMENT SETUP ..........................................................................................3
Try it Option Online.................................................................................................................................3
Local Environment Setup.........................................................................................................................3
Popular Java Editors................................................................................................................................4
3. JAVA 8 ─ LAMBDA EXPRESSIONS..........................................................................................5
Syntax .....................................................................................................................................................5
Lambda Expressions Example..................................................................................................................5
Scope ......................................................................................................................................................7
4. JAVA 8 ─ METHOD REFERENCES..........................................................................................9
Method Reference Example ....................................................................................................................9
5. JAVA 8 ─ FUNCTIONAL INTERFACES...................................................................................11
Functional Interface Example................................................................................................................14
6. JAVA 8 ─ DEFAULT METHODS............................................................................................17
Multiple Defaults ..................................................................................................................................17
Static Default Methods .........................................................................................................................18
Default Method Example ......................................................................................................................18
iii
7. JAVA 8 ─ STREAMS.............................................................................................................20
What is Stream?....................................................................................................................................20
Generating Streams ..............................................................................................................................20
forEach..................................................................................................................................................21
map.......................................................................................................................................................21
filter ......................................................................................................................................................21
limit.......................................................................................................................................................21
sorted....................................................................................................................................................22
Parallel Processing ................................................................................................................................22
Collectors ..............................................................................................................................................22
Statistics................................................................................................................................................22
Stream Example ....................................................................................................................................23
8. JAVA 8 ─ OPTIONAL CLASS.................................................................................................30
Class Declaration...................................................................................................................................30
Class Methods.......................................................................................................................................30
Optional Example..................................................................................................................................31
9. JAVA 8 ─ NASHORN JAVASCRIPT ENGINE...........................................................................33
jjs ..........................................................................................................................................................33
Calling JavaScript from Java ..................................................................................................................34
Calling Java from JavaScript ..................................................................................................................35
10. JAVA 8 ─ NEW DATE-TIME API...........................................................................................36
Local Date-Time API ..............................................................................................................................36
Zoned Date-Time API ............................................................................................................................38
Chrono Units Enum ...............................................................................................................................39
Period & Duration .................................................................................................................................40
iv
Temporal Adjusters...............................................................................................................................42
Backward Compatibility ........................................................................................................................43
11. JAVA 8 ─ BASE64................................................................................................................45
Nested Classes ......................................................................................................................................45
Methods................................................................................................................................................45
Methods Inherited ................................................................................................................................46
5
JAVA 8 is a major feature release of JAVA programming language development. Its initial
version was released on 18 March 2014. With the Java 8 release, Java provided supports for
functional programming, new JavaScript engine, new APIs for date time manipulation, new
streaming API, etc.
NewFeatures
 Lambda expression - Adds functional processing capability to Java.
 Method references - Referencing functions by their names instead of invoking them
directly. Using functions as parameter.
 Default method - Interface to have default method implementation.
 New tools - New compiler tools and utilities are added like ‘jdeps’ to figure out
dependencies.
 Stream API - New stream API to facilitate pipeline processing.
 Date Time API - Improved date time API.
 Optional - Emphasis on best practices to handle null values properly.
 Nashorn, JavaScript Engine - A Java-based engine to execute JavaScript code.
Consider the following code snippet.
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class Java8Tester {
public static void main(String args[]){
List<String> names1 = new ArrayList<String>();
names1.add("Mahesh ");
names1.add("Suresh ");
names1.add("Ramesh ");
1. JAVA 8 ─ OVERVIEW
6
names1.add("Naresh ");
names1.add("Kalpesh ");
List<String> names2 = new ArrayList<String>();
names2.add("Mahesh ");
names2.add("Suresh ");
names2.add("Ramesh ");
names2.add("Naresh ");
names2.add("Kalpesh ");
Java8Tester tester = new Java8Tester();
System.out.println("Sort using Java 7 syntax: ");
tester.sortUsingJava7(names1);
System.out.println(names1);
System.out.println("Sort using Java 8 syntax: ");
tester.sortUsingJava8(names2);
System.out.println(names2);
}
private void sortUsingJava7(List<String> names){
//sort using java 7
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
}
private void sortUsingJava8(List<String> names){
// sort using java 8
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
}
7
}
Run the program to get the following result.
Sort using Java 7 syntax:
[ Kalpesh Mahesh Naresh Ramesh Suresh ]
Sort using Java 8 syntax:
[ Kalpesh Mahesh Naresh Ramesh Suresh ]
Here the sortUsingJava8() method uses sort function with a lambda expression as
parameter to get the sorting criteria.
8
TryitOptionOnline
We have set up the Java Programming environment online, so that you can compile and
execute all the available examples online. It gives you confidence in what you are reading
and enables you to verify the programs with different options. Feel free to modify any example
and execute it online.
Try the following example using our online compiler available at
http://www.compileonline.com/
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
}
}
For most of the examples given in this tutorial, you will find a Try it option in our website
code sections at the top right corner that will take you to the online compiler. So just make
use of it and enjoy your learning.
LocalEnvironmentSetup
If you want to set up your own environment for Java programming language, then this section
guides you through the whole process. Please follow the steps given below to set up your
Java environment.
Java SE can be downloaded for free from the following link:
http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html
You download a version based on your operating system.
Follow the instructions to download Java, and run the .exe to install Java on your machine.
Once you have installed Java on your machine, you would need to set environment variables
to point to correct installation directories.
Setting Up the Path for Windows 2000/XP
Assuming you have installed Java in c:Program Filesjavajdk directory:
1. Right-click on 'My Computer' and select 'Properties'.
2. JAVA 8 ─ ENVIRONMENT SETUP
9
2. Click on the 'Environment variables' button under the 'Advanced' tab.
3. Now, alter the 'Path' variable so that it also contains the path to the Java executable.
For example, if the path is currently set to 'C:WINDOWSSYSTEM32', then change
your path to read 'C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin'.
Setting Up the Path for Windows 95/98/ME
Assuming you have installed Java in c:Program Filesjavajdk directory:
 Edit the 'C:autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:Program Filesjavajdkbin'
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java binaries have been
installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at the end
of your '.bashrc: export PATH=/path/to/java:$PATH'
PopularJavaEditors
To write Java programs, you need a text editor. There are even more sophisticated IDEs
available in the market. But for now, you can consider one of the following:
 Notepad: On Windows machine, you can use any simple text editor like Notepad
(recommended for this tutorial) or TextPad.
 Netbeans: It is a Java IDE that is open-source and free. It can be downloaded
from http://www.netbeans.org/index.html.
 Eclipse: It is also a Java IDE developed by the Eclipse open-source community and
can be downloaded from http://www.eclipse.org/.
10
Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java
8. Lambda expression facilitates functional programming, and simplifies the development a
lot.
Syntax
A lambda expression is characterized by the following syntax.
parameter -> expression body
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.
LambdaExpressionsExample
Create the following Java program using any editor of your choice in, say, C:> JAVA.
Java8Tester.java
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
//with type declaration
MathOperation addition = (int a, int b) -> a + b;
//with out type declaration
3. JAVA 8 ─ LAMBDA EXPRESSIONS
11
MathOperation subtraction = (a, b) -> a - b;
//with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> { return a * b; };
//without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
//with parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
//without parenthesis
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Mahesh");
greetService2.sayMessage("Suresh");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
12
}
}
Verify the Result
Compile the class using javac compiler as follows:
C:JAVA>javac Java8Tester.java
Now run the Java8Tester as follows:
C:JAVA>java Java8Tester
It should produce the following output:
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Following are the important points to be considered in the above example.
 Lambda expressions are used primarily to define inline implementation of a functional
interface, i.e., an interface with a single method only. In the above example, we've
used various types of lambda expressions to define the operation method of
MathOperation interface. Then we have defined the implementation of sayMessage of
GreetingService.
 Lambda expression eliminates the need of anonymous class and gives a very simple
yet powerful functional programming capability to Java.
Scope
Using lambda expression, you can refer to any final variable or effectively final variable (which
is assigned only once). Lambda expression throws a compilation error, if a variable is assigned
a value the second time.
Scope Example
Create the following Java program using any editor of your choice in, say, C:> JAVA.
Java8Tester.java
13
public class Java8Tester {
final static String salutation = "Hello! ";
public static void main(String args[]){
GreetingService greetService1 = message ->
System.out.println(salutation + message);
greetService1.sayMessage("Mahesh");
}
interface GreetingService {
void sayMessage(String message);
}
}
Verify the Result
Compile the class using javac compiler as follows:
C:JAVA>javac Java8Tester.java
Now run the Java8Tester as follows:
C:JAVA>java Java8Tester
It should produce the following output:
Hello! Mahesh
14
Method references help to point to methods by their names. A method reference is described
using "::" symbol. A method reference can be used to point the following types of methods:
 Static methods
 Instance methods
 Constructors using new operator (TreeSet::new)
MethodReferenceExample
Create the following Java program using any editor of your choice in, say, C:> JAVA.
Java8Tester.java
import java.util.List;
import java.util.ArrayList;
public class Java8Tester {
public static void main(String args[]){
List names = new ArrayList();
names.add("Mahesh");
names.add("Suresh");
names.add("Ramesh");
names.add("Naresh");
names.add("Kalpesh");
names.forEach(System.out::println);
}
}
Here we have passed System.out::println method as a static method reference.
Verify the Result
4. JAVA 8 ─ METHOD REFERENCES
15
Compile the class using javac compiler as follows:
C:JAVA>javac Java8Tester.java
Now run the Java8Tester as follows:
C:JAVA>java Java8Tester
It should produce the following output:
Mahesh
Suresh
Ramesh
Naresh
Kalpesh
16
End of ebook preview
If you liked what you saw…
Buy it from our store @ https://store.tutorialspoint.com

More Related Content

What's hot

Netlogo v5.0.5 user manual
Netlogo v5.0.5 user manualNetlogo v5.0.5 user manual
Netlogo v5.0.5 user manual
pemaLsi
 
Nodejs tutorial
Nodejs tutorialNodejs tutorial
Nodejs tutorial
HarikaReddy115
 
Rit 8.5.0 integration testing training student's guide
Rit 8.5.0 integration testing training student's guideRit 8.5.0 integration testing training student's guide
Rit 8.5.0 integration testing training student's guideDarrel Rader
 
Rit 8.5.0 platform training student's guide
Rit 8.5.0 platform training student's guideRit 8.5.0 platform training student's guide
Rit 8.5.0 platform training student's guideDarrel Rader
 
Operating system tutorial
Operating system tutorialOperating system tutorial
Operating system tutorial
HarikaReddy115
 
Ipad Usability 2nd Edition
Ipad Usability 2nd EditionIpad Usability 2nd Edition
Ipad Usability 2nd Edition
jamiewaltz
 
Rit 8.5.0 virtualization training student's guide
Rit 8.5.0 virtualization training student's guideRit 8.5.0 virtualization training student's guide
Rit 8.5.0 virtualization training student's guideDarrel Rader
 
2010 06 ess user guide_v5
2010 06 ess user guide_v52010 06 ess user guide_v5
2010 06 ess user guide_v5ikhsan
 
Gstar cad 2018 user guide
Gstar cad 2018 user guideGstar cad 2018 user guide
Gstar cad 2018 user guide
Eleftheria Zoaki
 
Rit 8.5.0 performance testing training student's guide
Rit 8.5.0 performance testing training student's guideRit 8.5.0 performance testing training student's guide
Rit 8.5.0 performance testing training student's guideDarrel Rader
 
Chitubox user manual v1.0 en
Chitubox user manual v1.0 enChitubox user manual v1.0 en
Chitubox user manual v1.0 en
DaveRFlorizone
 
Android Programing Course Material
Android Programing Course Material Android Programing Course Material
Android Programing Course Material
Shady Selim
 
Developers best practices_tutorial
Developers best practices_tutorialDevelopers best practices_tutorial
Developers best practices_tutorialVinay H G
 

What's hot (16)

Netlogo v5.0.5 user manual
Netlogo v5.0.5 user manualNetlogo v5.0.5 user manual
Netlogo v5.0.5 user manual
 
Nodejs tutorial
Nodejs tutorialNodejs tutorial
Nodejs tutorial
 
Tutorials proteus schematic
Tutorials proteus schematicTutorials proteus schematic
Tutorials proteus schematic
 
Rit 8.5.0 integration testing training student's guide
Rit 8.5.0 integration testing training student's guideRit 8.5.0 integration testing training student's guide
Rit 8.5.0 integration testing training student's guide
 
Rit 8.5.0 platform training student's guide
Rit 8.5.0 platform training student's guideRit 8.5.0 platform training student's guide
Rit 8.5.0 platform training student's guide
 
Operating system tutorial
Operating system tutorialOperating system tutorial
Operating system tutorial
 
Ipad Usability 2nd Edition
Ipad Usability 2nd EditionIpad Usability 2nd Edition
Ipad Usability 2nd Edition
 
Rit 8.5.0 virtualization training student's guide
Rit 8.5.0 virtualization training student's guideRit 8.5.0 virtualization training student's guide
Rit 8.5.0 virtualization training student's guide
 
2010 06 ess user guide_v5
2010 06 ess user guide_v52010 06 ess user guide_v5
2010 06 ess user guide_v5
 
Bp ttutorial
Bp ttutorialBp ttutorial
Bp ttutorial
 
Gstar cad 2018 user guide
Gstar cad 2018 user guideGstar cad 2018 user guide
Gstar cad 2018 user guide
 
Rit 8.5.0 performance testing training student's guide
Rit 8.5.0 performance testing training student's guideRit 8.5.0 performance testing training student's guide
Rit 8.5.0 performance testing training student's guide
 
Chitubox user manual v1.0 en
Chitubox user manual v1.0 enChitubox user manual v1.0 en
Chitubox user manual v1.0 en
 
Android Programing Course Material
Android Programing Course Material Android Programing Course Material
Android Programing Course Material
 
Developers best practices_tutorial
Developers best practices_tutorialDevelopers best practices_tutorial
Developers best practices_tutorial
 
ISVForce Guide NEW
ISVForce Guide NEWISVForce Guide NEW
ISVForce Guide NEW
 

Similar to Java8 tutorial

Agile tutorial
Agile tutorialAgile tutorial
Agile tutorial
HarikaReddy115
 
agile_tutorial.pdf
agile_tutorial.pdfagile_tutorial.pdf
agile_tutorial.pdf
HODCA1
 
Agile testing tutorial
Agile testing tutorialAgile testing tutorial
Agile testing tutorial
HarikaReddy115
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
Ashoka Vanjare
 
Soapui tutorial
Soapui tutorialSoapui tutorial
Soapui tutorial
HarikaReddy115
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
HarikaReddy115
 
javascript_tutorial.pdf
javascript_tutorial.pdfjavascript_tutorial.pdf
javascript_tutorial.pdf
kaouthar20
 
Java jsp tutorial
Java jsp tutorialJava jsp tutorial
Java jsp tutorial
Ashoka Vanjare
 
Jsp tutorial
Jsp tutorialJsp tutorial
Jsp tutorial
mamog
 
Software engineering
Software engineering Software engineering
Software engineering
Pallav
 
Software Engineering Overview
Software Engineering Overview Software Engineering Overview
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
Doeun KOCH
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
kshitij chaurasiya
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
Bhawna Khanduri
 
Sdlc tutorial
Sdlc tutorialSdlc tutorial
Sdlc tutorial
HarikaReddy115
 
Kotlin tutorial
Kotlin tutorialKotlin tutorial
Kotlin tutorial
truck
 
Javafx tutorial
Javafx tutorialJavafx tutorial
Javafx tutorial
Shaman Gupta
 
Javafx tutorial
Javafx tutorialJavafx tutorial
Javafx tutorial
sloumaallagui1
 

Similar to Java8 tutorial (20)

Agile tutorial
Agile tutorialAgile tutorial
Agile tutorial
 
agile_tutorial.pdf
agile_tutorial.pdfagile_tutorial.pdf
agile_tutorial.pdf
 
Agile testing tutorial
Agile testing tutorialAgile testing tutorial
Agile testing tutorial
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
 
Soapui tutorial
Soapui tutorialSoapui tutorial
Soapui tutorial
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
javascript_tutorial.pdf
javascript_tutorial.pdfjavascript_tutorial.pdf
javascript_tutorial.pdf
 
Jsp tutorial (1)
Jsp tutorial (1)Jsp tutorial (1)
Jsp tutorial (1)
 
Java jsp tutorial
Java jsp tutorialJava jsp tutorial
Java jsp tutorial
 
Jsp tutorial
Jsp tutorialJsp tutorial
Jsp tutorial
 
Software engineering
Software engineering Software engineering
Software engineering
 
Software Engineering Overview
Software Engineering Overview Software Engineering Overview
Software Engineering Overview
 
Javaeetutorial6
Javaeetutorial6Javaeetutorial6
Javaeetutorial6
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
 
Sdlc tutorial
Sdlc tutorialSdlc tutorial
Sdlc tutorial
 
Kotlin tutorial
Kotlin tutorialKotlin tutorial
Kotlin tutorial
 
Javafx tutorial
Javafx tutorialJavafx tutorial
Javafx tutorial
 
Javafx tutorial
Javafx tutorialJavafx tutorial
Javafx tutorial
 

More from HarikaReddy115

Dbms tutorial
Dbms tutorialDbms tutorial
Dbms tutorial
HarikaReddy115
 
Data structures algorithms_tutorial
Data structures algorithms_tutorialData structures algorithms_tutorial
Data structures algorithms_tutorial
HarikaReddy115
 
Wireless communication tutorial
Wireless communication tutorialWireless communication tutorial
Wireless communication tutorial
HarikaReddy115
 
Cryptography tutorial
Cryptography tutorialCryptography tutorial
Cryptography tutorial
HarikaReddy115
 
Cosmology tutorial
Cosmology tutorialCosmology tutorial
Cosmology tutorial
HarikaReddy115
 
Control systems tutorial
Control systems tutorialControl systems tutorial
Control systems tutorial
HarikaReddy115
 
Computer logical organization_tutorial
Computer logical organization_tutorialComputer logical organization_tutorial
Computer logical organization_tutorial
HarikaReddy115
 
Computer fundamentals tutorial
Computer fundamentals tutorialComputer fundamentals tutorial
Computer fundamentals tutorial
HarikaReddy115
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
HarikaReddy115
 
Communication technologies tutorial
Communication technologies tutorialCommunication technologies tutorial
Communication technologies tutorial
HarikaReddy115
 
Biometrics tutorial
Biometrics tutorialBiometrics tutorial
Biometrics tutorial
HarikaReddy115
 
Behavior driven development_tutorial
Behavior driven development_tutorialBehavior driven development_tutorial
Behavior driven development_tutorial
HarikaReddy115
 
Basics of computers_tutorial
Basics of computers_tutorialBasics of computers_tutorial
Basics of computers_tutorial
HarikaReddy115
 
Basics of computer_science_tutorial
Basics of computer_science_tutorialBasics of computer_science_tutorial
Basics of computer_science_tutorial
HarikaReddy115
 
Basic electronics tutorial
Basic electronics tutorialBasic electronics tutorial
Basic electronics tutorial
HarikaReddy115
 
Auditing tutorial
Auditing tutorialAuditing tutorial
Auditing tutorial
HarikaReddy115
 
Artificial neural network_tutorial
Artificial neural network_tutorialArtificial neural network_tutorial
Artificial neural network_tutorial
HarikaReddy115
 
Artificial intelligence tutorial
Artificial intelligence tutorialArtificial intelligence tutorial
Artificial intelligence tutorial
HarikaReddy115
 
Antenna theory tutorial
Antenna theory tutorialAntenna theory tutorial
Antenna theory tutorial
HarikaReddy115
 
Analog communication tutorial
Analog communication tutorialAnalog communication tutorial
Analog communication tutorial
HarikaReddy115
 

More from HarikaReddy115 (20)

Dbms tutorial
Dbms tutorialDbms tutorial
Dbms tutorial
 
Data structures algorithms_tutorial
Data structures algorithms_tutorialData structures algorithms_tutorial
Data structures algorithms_tutorial
 
Wireless communication tutorial
Wireless communication tutorialWireless communication tutorial
Wireless communication tutorial
 
Cryptography tutorial
Cryptography tutorialCryptography tutorial
Cryptography tutorial
 
Cosmology tutorial
Cosmology tutorialCosmology tutorial
Cosmology tutorial
 
Control systems tutorial
Control systems tutorialControl systems tutorial
Control systems tutorial
 
Computer logical organization_tutorial
Computer logical organization_tutorialComputer logical organization_tutorial
Computer logical organization_tutorial
 
Computer fundamentals tutorial
Computer fundamentals tutorialComputer fundamentals tutorial
Computer fundamentals tutorial
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
 
Communication technologies tutorial
Communication technologies tutorialCommunication technologies tutorial
Communication technologies tutorial
 
Biometrics tutorial
Biometrics tutorialBiometrics tutorial
Biometrics tutorial
 
Behavior driven development_tutorial
Behavior driven development_tutorialBehavior driven development_tutorial
Behavior driven development_tutorial
 
Basics of computers_tutorial
Basics of computers_tutorialBasics of computers_tutorial
Basics of computers_tutorial
 
Basics of computer_science_tutorial
Basics of computer_science_tutorialBasics of computer_science_tutorial
Basics of computer_science_tutorial
 
Basic electronics tutorial
Basic electronics tutorialBasic electronics tutorial
Basic electronics tutorial
 
Auditing tutorial
Auditing tutorialAuditing tutorial
Auditing tutorial
 
Artificial neural network_tutorial
Artificial neural network_tutorialArtificial neural network_tutorial
Artificial neural network_tutorial
 
Artificial intelligence tutorial
Artificial intelligence tutorialArtificial intelligence tutorial
Artificial intelligence tutorial
 
Antenna theory tutorial
Antenna theory tutorialAntenna theory tutorial
Antenna theory tutorial
 
Analog communication tutorial
Analog communication tutorialAnalog communication tutorial
Analog communication tutorial
 

Recently uploaded

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 

Recently uploaded (20)

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 

Java8 tutorial

  • 1.
  • 2. i AbouttheTutorial Java 8 is the most awaited and is a major feature release of Java programming language. This is an introductory tutorial that explains the basic-to-advanced features of Java 8 and their usage in a simple and intuitive way. Audience This tutorial will be useful for most Java developers, starting from beginners to experts. After completing this tutorial, you will find yourself at a moderate level of expertise in Java 8, from where you can take yourself to next levels. Prerequisites Knowledge of basic Java programming language is the only prerequisite for learning the concepts explained in this tutorial. Copyright&Disclaimer  Copyright 2015 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com
  • 3. ii TableofContents About the Tutorial....................................................................................................................................i Audience..................................................................................................................................................i Prerequisites............................................................................................................................................i Copyright & Disclaimer.............................................................................................................................i Table of Contents....................................................................................................................................ii 1. JAVA 8 ─ OVERVIEW ............................................................................................................1 New Features..........................................................................................................................................1 2. JAVA 8 ─ ENVIRONMENT SETUP ..........................................................................................3 Try it Option Online.................................................................................................................................3 Local Environment Setup.........................................................................................................................3 Popular Java Editors................................................................................................................................4 3. JAVA 8 ─ LAMBDA EXPRESSIONS..........................................................................................5 Syntax .....................................................................................................................................................5 Lambda Expressions Example..................................................................................................................5 Scope ......................................................................................................................................................7 4. JAVA 8 ─ METHOD REFERENCES..........................................................................................9 Method Reference Example ....................................................................................................................9 5. JAVA 8 ─ FUNCTIONAL INTERFACES...................................................................................11 Functional Interface Example................................................................................................................14 6. JAVA 8 ─ DEFAULT METHODS............................................................................................17 Multiple Defaults ..................................................................................................................................17 Static Default Methods .........................................................................................................................18 Default Method Example ......................................................................................................................18
  • 4. iii 7. JAVA 8 ─ STREAMS.............................................................................................................20 What is Stream?....................................................................................................................................20 Generating Streams ..............................................................................................................................20 forEach..................................................................................................................................................21 map.......................................................................................................................................................21 filter ......................................................................................................................................................21 limit.......................................................................................................................................................21 sorted....................................................................................................................................................22 Parallel Processing ................................................................................................................................22 Collectors ..............................................................................................................................................22 Statistics................................................................................................................................................22 Stream Example ....................................................................................................................................23 8. JAVA 8 ─ OPTIONAL CLASS.................................................................................................30 Class Declaration...................................................................................................................................30 Class Methods.......................................................................................................................................30 Optional Example..................................................................................................................................31 9. JAVA 8 ─ NASHORN JAVASCRIPT ENGINE...........................................................................33 jjs ..........................................................................................................................................................33 Calling JavaScript from Java ..................................................................................................................34 Calling Java from JavaScript ..................................................................................................................35 10. JAVA 8 ─ NEW DATE-TIME API...........................................................................................36 Local Date-Time API ..............................................................................................................................36 Zoned Date-Time API ............................................................................................................................38 Chrono Units Enum ...............................................................................................................................39 Period & Duration .................................................................................................................................40
  • 5. iv Temporal Adjusters...............................................................................................................................42 Backward Compatibility ........................................................................................................................43 11. JAVA 8 ─ BASE64................................................................................................................45 Nested Classes ......................................................................................................................................45 Methods................................................................................................................................................45 Methods Inherited ................................................................................................................................46
  • 6. 5 JAVA 8 is a major feature release of JAVA programming language development. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided supports for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API, etc. NewFeatures  Lambda expression - Adds functional processing capability to Java.  Method references - Referencing functions by their names instead of invoking them directly. Using functions as parameter.  Default method - Interface to have default method implementation.  New tools - New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.  Stream API - New stream API to facilitate pipeline processing.  Date Time API - Improved date time API.  Optional - Emphasis on best practices to handle null values properly.  Nashorn, JavaScript Engine - A Java-based engine to execute JavaScript code. Consider the following code snippet. import java.util.Collections; import java.util.List; import java.util.ArrayList; import java.util.Comparator; public class Java8Tester { public static void main(String args[]){ List<String> names1 = new ArrayList<String>(); names1.add("Mahesh "); names1.add("Suresh "); names1.add("Ramesh "); 1. JAVA 8 ─ OVERVIEW
  • 7. 6 names1.add("Naresh "); names1.add("Kalpesh "); List<String> names2 = new ArrayList<String>(); names2.add("Mahesh "); names2.add("Suresh "); names2.add("Ramesh "); names2.add("Naresh "); names2.add("Kalpesh "); Java8Tester tester = new Java8Tester(); System.out.println("Sort using Java 7 syntax: "); tester.sortUsingJava7(names1); System.out.println(names1); System.out.println("Sort using Java 8 syntax: "); tester.sortUsingJava8(names2); System.out.println(names2); } private void sortUsingJava7(List<String> names){ //sort using java 7 Collections.sort(names, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); } private void sortUsingJava8(List<String> names){ // sort using java 8 Collections.sort(names, (s1, s2) -> s1.compareTo(s2)); }
  • 8. 7 } Run the program to get the following result. Sort using Java 7 syntax: [ Kalpesh Mahesh Naresh Ramesh Suresh ] Sort using Java 8 syntax: [ Kalpesh Mahesh Naresh Ramesh Suresh ] Here the sortUsingJava8() method uses sort function with a lambda expression as parameter to get the sorting criteria.
  • 9. 8 TryitOptionOnline We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online. Try the following example using our online compiler available at http://www.compileonline.com/ public class MyFirstJavaProgram { public static void main(String []args) { System.out.println("Hello World"); } } For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning. LocalEnvironmentSetup If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment. Java SE can be downloaded for free from the following link: http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html You download a version based on your operating system. Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories. Setting Up the Path for Windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory: 1. Right-click on 'My Computer' and select 'Properties'. 2. JAVA 8 ─ ENVIRONMENT SETUP
  • 10. 9 2. Click on the 'Environment variables' button under the 'Advanced' tab. 3. Now, alter the 'Path' variable so that it also contains the path to the Java executable. For example, if the path is currently set to 'C:WINDOWSSYSTEM32', then change your path to read 'C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin'. Setting Up the Path for Windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory:  Edit the 'C:autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:Program Filesjavajdkbin' Setting Up the Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. For example, if you use bash as your shell, then you would add the following line at the end of your '.bashrc: export PATH=/path/to/java:$PATH' PopularJavaEditors To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:  Notepad: On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or TextPad.  Netbeans: It is a Java IDE that is open-source and free. It can be downloaded from http://www.netbeans.org/index.html.  Eclipse: It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from http://www.eclipse.org/.
  • 11. 10 Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot. Syntax A lambda expression is characterized by the following syntax. parameter -> expression body 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. LambdaExpressionsExample Create the following Java program using any editor of your choice in, say, C:> JAVA. Java8Tester.java public class Java8Tester { public static void main(String args[]){ Java8Tester tester = new Java8Tester(); //with type declaration MathOperation addition = (int a, int b) -> a + b; //with out type declaration 3. JAVA 8 ─ LAMBDA EXPRESSIONS
  • 12. 11 MathOperation subtraction = (a, b) -> a - b; //with return statement along with curly braces MathOperation multiplication = (int a, int b) -> { return a * b; }; //without return statement and without curly braces MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); //with parenthesis GreetingService greetService1 = message -> System.out.println("Hello " + message); //without parenthesis GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b);
  • 13. 12 } } Verify the Result Compile the class using javac compiler as follows: C:JAVA>javac Java8Tester.java Now run the Java8Tester as follows: C:JAVA>java Java8Tester It should produce the following output: 10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh Following are the important points to be considered in the above example.  Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.  Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java. Scope Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time. Scope Example Create the following Java program using any editor of your choice in, say, C:> JAVA. Java8Tester.java
  • 14. 13 public class Java8Tester { final static String salutation = "Hello! "; public static void main(String args[]){ GreetingService greetService1 = message -> System.out.println(salutation + message); greetService1.sayMessage("Mahesh"); } interface GreetingService { void sayMessage(String message); } } Verify the Result Compile the class using javac compiler as follows: C:JAVA>javac Java8Tester.java Now run the Java8Tester as follows: C:JAVA>java Java8Tester It should produce the following output: Hello! Mahesh
  • 15. 14 Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods:  Static methods  Instance methods  Constructors using new operator (TreeSet::new) MethodReferenceExample Create the following Java program using any editor of your choice in, say, C:> JAVA. Java8Tester.java import java.util.List; import java.util.ArrayList; public class Java8Tester { public static void main(String args[]){ List names = new ArrayList(); names.add("Mahesh"); names.add("Suresh"); names.add("Ramesh"); names.add("Naresh"); names.add("Kalpesh"); names.forEach(System.out::println); } } Here we have passed System.out::println method as a static method reference. Verify the Result 4. JAVA 8 ─ METHOD REFERENCES
  • 16. 15 Compile the class using javac compiler as follows: C:JAVA>javac Java8Tester.java Now run the Java8Tester as follows: C:JAVA>java Java8Tester It should produce the following output: Mahesh Suresh Ramesh Naresh Kalpesh
  • 17. 16 End of ebook preview If you liked what you saw… Buy it from our store @ https://store.tutorialspoint.com