SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
Darrel 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 guide
Darrel Rader
 
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
Darrel Rader
 
2010 06 ess user guide_v5
2010 06 ess user guide_v52010 06 ess user guide_v5
2010 06 ess user guide_v5
ikhsan
 
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
Darrel Rader
 
Developers best practices_tutorial
Developers best practices_tutorialDevelopers best practices_tutorial
Developers best practices_tutorial
Vinay H G
 

La actualidad más candente (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 a Java8 tutorial

javascript_tutorial.pdf
javascript_tutorial.pdfjavascript_tutorial.pdf
javascript_tutorial.pdf
kaouthar20
 
Kotlin tutorial
Kotlin tutorialKotlin tutorial
Kotlin tutorial
truck
 

Similar a Java8 tutorial (20)

agile_tutorial.pdf
agile_tutorial.pdfagile_tutorial.pdf
agile_tutorial.pdf
 
Agile tutorial
Agile tutorialAgile tutorial
Agile tutorial
 
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
Jsp tutorialJsp tutorial
Jsp tutorial
 
Jsp tutorial (1)
Jsp tutorial (1)Jsp tutorial (1)
Jsp tutorial (1)
 
Java jsp tutorial
Java jsp tutorialJava jsp tutorial
Java jsp tutorial
 
Software Engineering Overview
Software Engineering Overview Software Engineering Overview
Software Engineering Overview
 
Software engineering
Software engineering Software engineering
Software engineering
 
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
 

Más de HarikaReddy115

Más de 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
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Último (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 

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