100% found this document useful (1 vote)
123 views

Regular Expression

The document discusses Java regular expressions (regex). It provides: 1) An overview of the Java regex API and its main classes - Pattern, Matcher, and classes for exceptions. 2) Descriptions of the Matcher and Pattern classes and their common methods. 3) Examples of using regex character classes, quantifiers, and metacharacters in Java regex patterns. 4) Two questions with examples of regex patterns to validate strings.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
123 views

Regular Expression

The document discusses Java regular expressions (regex). It provides: 1) An overview of the Java regex API and its main classes - Pattern, Matcher, and classes for exceptions. 2) Descriptions of the Matcher and Pattern classes and their common methods. 3) Examples of using regex character classes, quantifiers, and metacharacters in Java regex patterns. 4) Two questions with examples of regex patterns to validate strings.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

REGULAR EXPRESSION

Java Regex
The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.

It is widely used to define the constraint on strings such as password and email validation. After learning
Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.

java.util.regex package

The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package
provides following classes and interfaces for regular expressions.

1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class

Matcher class
It implements the MatchResult interface. It is a regex engine which is used to perform match operations
on a character sequence.
No Method Description
.

1 boolean matches() test whether the regular expression matches the pattern.

2 boolean find() finds the next expression that matches the pattern.

3 boolean find(int finds the next expression that matches the pattern from the given start
start) number.

4 String group() returns the matched subsequence.

5 int start() returns the starting index of the matched subsequence.

6 int end() returns the ending index of the matched subsequence.

7 int groupCount() returns the total number of the matched subsequence.

Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.

No Method Description
.

1 static Pattern compile(String regex) compiles the given regex and returns the instance of the
Pattern.

2 Matcher matcher(CharSequence creates a matcher that matches the given input with the
input) pattern.

3 static boolean matches(String It works as the combination of compile and matcher


regex, CharSequence input) methods. It compiles the regular expression and matches
the given input with the pattern.

4 String[] split(CharSequence input) splits the given input string around matches of given
pattern.

5 String pattern() returns the regex pattern.


Example of Java Regular Expressions
There are three ways to write the regex example in Java.

1. import java.util.regex.*;  
2. public class RegexExample1{  
3. public static void main(String args[]){  
4. //1st way  
5. Pattern p = Pattern.compile(".s");//. represents single character  
6. Matcher m = p.matcher("as");  
7. boolean b = m.matches();  
8.   
9. //2nd way  
10. boolean b2=Pattern.compile(".s").matcher("as").matches();  
11.   
12. //3rd way  
13. boolean b3 = Pattern.matches(".s", "as");  
14.   
15. System.out.println(b+" "+b2+" "+b3);  
16. }}  

Output

true true true

Regular Expression . Example


The . (dot) represents a single character.

1. import java.util.regex.*;  
2. class RegexExample2{  
3. public static void main(String args[]){  
4. System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)  
5. System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)  
6. System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)  
7. System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)  
8. System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)  
9. }}  

Regex Character classes


No. Character Class Description

1 [abc] a, b, or c (simple class)

2 [^abc] Any character except a, b, or c (negation)

3 [a-zA-Z] a through z or A through Z, inclusive (range)

4 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)

5 [a-z&&[def]] d, e, or f (intersection)

6 [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)

7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Regular Expression Character classes Example


1. import java.util.regex.*;  
2. class RegexExample3{  
3. public static void main(String args[]){  
4. System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)  
5. System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)  
6. System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more than once)  
7. }}  

Regex Quantifiers
The quantifiers specify the number of occurrences of a character.

Regex Description

X? X occurs once or not at all

X+ X occurs once or more times


X* X occurs zero or more times

X{n} X occurs n times only

X{n,} X occurs n or more times

X{y,z} X occurs at least y times but less than z times

Regular Expression Character classes and Quantifiers Example


1. import java.util.regex.*;  
2. class RegexExample4{  
3. public static void main(String args[]){  
4. System.out.println("? quantifier ....");  
5. System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)  
6. System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)  
7. System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time) 
 
8. System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)  
9. System.out.println(Pattern.matches("[amn]?", "m"));//false (a or m or n must come one time)  
10.   
11. System.out.println("+ quantifier ....");  
12. System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)  
13. System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)  
14. System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)  
15. System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)  
16.   
17. System.out.println("* quantifier ....");  
18. System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more time
s)  
19.   
20. }}  

Regex Metacharacters
The regular expression metacharacters work as shortcodes.
Regex Description

. Any character (may or may not match terminator)

\d Any digits, short of [0-9]

\D Any non-digit, short for [^0-9]

\s Any whitespace character, short for [\t\n\x0B\f\r]

\S Any non-whitespace character, short for [^\s]

\w Any word character, short for [a-zA-Z_0-9]

\W Any non-word character, short for [^\w]

\b A word boundary

\B A non word boundary

Regular Expression Metacharacters Example


1. import java.util.regex.*;  
2. class RegexExample5{  
3. public static void main(String args[]){  
4. System.out.println("metacharacters d....");\\d means digit  
5.   
6. System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)  
7. System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)  
8. System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than once)  
9. System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)  
10.   
11. System.out.println("metacharacters D....");\\D means non-digit  
12.   
13. System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than once)  
14. System.out.println(Pattern.matches("\\D", "1"));//false (digit)  
15. System.out.println(Pattern.matches("\\D", "4443"));//false (digit)  
16. System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)  
17. System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)  
18.   
19. System.out.println("metacharacters D with quantifier....");  
20. System.out.println(Pattern.matches("\\D*", "mak"));//true (non-digit and may come 0 or more times)  
21.   
22. }}  

Regular Expression Question 1


1. /*Create a regular expression that accepts alphanumeric characters only.  
2. Its length must be six characters long only.*/  
3.   
4. import java.util.regex.*;  
5. class RegexExample6{  
6. public static void main(String args[]){  
7. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true  
8. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32"));//false (more than 6 char)  
9. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true  
10. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));//false ($ is not matched)  
11. }}  

Regular Expression Question 2


1. /*Create a regular expression that accepts 10 digit numeric characters 
2.  starting with 7, 8 or 9 only.*/  
3.   
4. import java.util.regex.*;  
5. class RegexExample7{  
6. public static void main(String args[]){  
7. System.out.println("by character classes and quantifiers ...");  
8. System.out.println(Pattern.matches("[789]{1}[0-9]{9}", "9953038949"));//true  
9. System.out.println(Pattern.matches("[789][0-9]{9}", "9953038949"));//true  
10.   
11. System.out.println(Pattern.matches("[789][0-9]{9}", "99530389490"));//false (11 characters)  
12. System.out.println(Pattern.matches("[789][0-9]{9}", "6953038949"));//false (starts from 6)  
13. System.out.println(Pattern.matches("[789][0-9]{9}", "8853038949"));//true  
14.   
15. System.out.println("by metacharacters ...");  
16. System.out.println(Pattern.matches("[789]{1}\\d{9}", "8853038949"));//true  
17. System.out.println(Pattern.matches("[789]{1}\\d{9}", "3853038949"));//false (starts from 3)  
18.   
19. }}  

Java Regex Finder Example


1. import java.util.regex.Pattern;  
2. import java.util.Scanner;  
3. import java.util.regex.Matcher;    
4. public class RegexExample8{    
5.     public static void main(String[] args){    
6.         Scanner sc=new Scanner(System.in);  
7.         while (true) {    
8.             System.out.println("Enter regex pattern:");  
9.             Pattern pattern = Pattern.compile(sc.nextLine());    
10.             System.out.println("Enter text:");  
11.             Matcher matcher = pattern.matcher(sc.nextLine());    
12.             boolean found = false;    
13.             while (matcher.find()) {    
14.                 System.out.println("I found the text "+matcher.group()+" starting at index "+    
15.                  matcher.start()+" and ending at index "+matcher.end());    
16.                 found = true;    
17.             }    
18.             if(!found){    
19.                 System.out.println("No match found.");    
20.             }    
21.         }    
22.     }    
23. }    

Output:

Enter regex pattern: java


Enter text: this is java, do you know java
I found the text java starting at index 8 and ending at index 12
I found the text java starting at index 26 and ending at index 30

Operators & Conditionals


Conditional Operator in Java
In Java, conditional operators check the condition and decides the desired result on the basis of both
conditions. In this section, we will discuss the conditional operator in Java.
Types of Conditional Operator
There are three types of the conditional operator in Java

o Conditional AND
o Conditional OR
o Ternary Operator

Operator Symbol

Conditional or Logical AND &&

Conditional or Logical OR ||

Ternary Operator ?:

Conditional AND
The operator is applied between two Boolean expressions. It is denoted by the two AND operators (&&).
It returns true if and only if both expressions are true, else returns false.

Expression1 Expression2 Expression1 && Expression2

True False False

False True False

False False False

True True True

Conditional OR
The operator is applied between two Boolean expressions. It is denoted by the two OR operator (||). It
returns true if any of the expression is true, else returns false.

Expression1 Expression2 Expression1 || Expression2


True True True

True False True

False True True

False False False

Let's create a Java program and use the conditional operator.

ConditionalOperatorExample.java

1. public class ConditionalOperatorExample  
2. {  
3. public static void main(String args[])   
4. {  
5. int x=5, y=4, z=7;  
6. System.out.println(x>y && x>z || y<z);  
7. System.out.println((x<z || y>z) && x<y);  
8. }  
9. }  

Output

true
false

Ternary Operator
The meaning of ternary is composed of three parts. The ternary operator (? :) consists of three
operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to
the variable. It is the only conditional operator that accepts three operands. It can be used instead of the
if-else statement. It makes the code much more easy, readable, and shorter.

Note: Every code using an if-else statement cannot be replaced with a ternary operator.

Syntax:

variable = (condition) ? expression1 : expression2  

The above statement states that if the condition returns true, expression1 gets executed, else
the expression2 gets executed and the final result stored in a variable.
Let's understand the ternary operator through the flowchart.

TernaryOperatorExample.java

1. public class TernaryOperatorExample  
2. {  
3. public static void main(String args[])   
4. {  
5. int x, y;  
6. x = 20;  
7. y = (x == 1) ? 61: 90;  
8. System.out.println("Value of y is: " +  y);  
9. y = (x == 20) ? 61: 90;  
10. System.out.println("Value of y is: " + y);  
11. }  
12. }  

Output

Value of y is: 90
Value of y is: 61
Let's see another example that evaluates the largest of three numbers using the ternary operator.

LargestNumberExample.java

1. public class LargestNumberExample  
2. {  
3. public static void main(String args[])  
4. {  
5. int x=69;  
6. int y=89;  
7. int z=79;  
8. int largestNumber= (x > y) ? (x > z ? x : z) : (y > z ? y : z);  
9. System.out.println("The largest numbers is:  "+largestNumber);  
10. }  
11. }  

Output

The largest number is: 89

In the above program, we have taken three variables x, y, and z having the values 69, 89, and 79,
respectively. The expression (x > y) ? (x > z ? x : z) : (y > z ? y : z) evaluates the largest number among
three numbers and store the final result in the variable largestNumber. Let's understand the execution
order of the expression.

First, it checks the expression (x > y). If it returns true the expression (x > z ? x : z) gets executed, else the
expression (y > z ? y : z) gets executed.

When the expression (x > z ? x : z) gets executed, it further checks the condition x > z. If the condition
returns true the value of x is returned, else the value of z is returned.

When the expression (y > z ? y : z) gets executed it further checks the condition y > z. If the condition
returns true the value of y is returned, else the value of z is returned.

Therefore, we get the largest of three numbers using the ternary operator.
Data Manipulation
What is Data Manipulation?
Data manipulation is the method of organizing data to make it easier to read or more designed or
structured. For instance, a collection of any kind of data could be organized in alphabetical order so that it
can be understood easily. On the other hand, it can be difficult to find information about any particular
employee in an organization if all the employees' information is not organized. Therefore, all the
employee's information could be organized in alphabetical order that makes it easier to find information
easily of any individual employee. Data manipulation helps website owners to monitor their sources of
traffic and their most popular pages. Hence, it is frequently used on web server logs.

Data manipulation is also used by accounting users or similar fields to organized data in order to figure
out product costs, future tax obligations, pricing patterns, etc. It also helps the stock market predictors to
forecast developments and predicts how stocks might perform in the adjacent future. Furthermore, data
manipulation may also use by computers to display information to users in a more realistic way on the
basis of web pages, the code in a software program, or data formatting.

The DML is used to manipulate data, which is a programming language. It short for Data Manipulation
Language that helps to modify data like adding, removing, and altering databases. It means that changing
the information in a way that can be read easily.

Objective of Data Manipulation


Data manipulation is a key feature for business operations and optimization. You need to deal with data
in a proper manner and manipulate it into meaningful information like doing trend analysis, financial data,
and consumer behavior. Data manipulation offers an organization multiple advantages; some are
discussed below:

20.2M

466

OOPs Concepts in Java

Next

Stay

o Consistent data: Data manipulation provides a way to organize your data inconsistent format
that makes it structured, which can be read easily and better understood. When you are collecting
data from different-different sources, you may not have a unified view; but data manipulation
provides you surety that the data is well-organized, structured, and stored consistently.
o Project data: Especially when it comes to finances, data manipulation is more useful as it helps to
provide more in-depth analysis by using historical data to project the future.
o Delete or neglect redundant data: Data manipulation helps to maintain your data and delete
unusable data that is always present.
o Overall, with the data, you can do many operations such as edit, delete, update, convert, and
incorporate data into a database. It helps to create more value from the data. If you do not know
how to use data in an effective manner, it becomes pointless. Therefore, it will be beneficial to
make better business decisions when you are able to organize your data accordingly.

Steps involved in Data Manipulation


Below there are some important steps given that may help you out to get started with data manipulation.

1. First of all, data manipulation is possible only if you have data. Therefore, you are required to
create a database that is generated from data sources.
2. This knowledge needs restructuring and reorganization, which could be done with data
manipulation that helps you to cleanse your information.
3. Then, you need to import a database and create it to get start work with data.
4. With the help of data manipulation, you can edit, delete, merge, or combine your information.
5. Finally, data analysis becomes easier at the time of manipulating data.

Why do use data manipulation?


It is more important to manipulate data for improving the growth of any business and organization. As
manipulation of data helps to use the information properly by organizing the raw data in a structural way,
which is crucial for boosting productivity, trend analysis, cutting costs, analyzing customer behavior, etc.
Below there are some examples of the benefits that describe the need for data manipulation.

Format consistency

Data manipulation offers a way to organize data in a unified format, which helps c-suit members to a
better understanding of business intelligence. The collection of data from various sources can be
unstructured, whereas DML (Data manipulation language) allows data to be consistently organized and
more transparent.

Historical overview

The manipulation of data can help you with making the right decisions by providing easy access to data
related to your previous projects. Also, it can help with required team size, budget allocation, and
deadline projections.

Efficiency

The manipulation of data provides efficiency in terms of collecting organized data or meaningful
information. You may not be aware that findings interfere or are redundant, information is relevant or not,
metrics have a low or significant impact. DML offers you the benefit of isolating and identify these facts
quickly.

In daily life, we also see data manipulation; if you are receiving calls from telemarketers, getting targeted
ads on the websites you visit or receiving emails, it is all done through data manipulation. It also helps in
your online behavior in terms of extracting relevant information. For example, when you are visiting any
website and share your email address at this site and agree to terms and conditions, it will monitor your
behavior and likely generate relevant data for you.

Data manipulation tips


One of the widely used tools for data manipulation is Microsoft Excel. Below there are some tips to work
on this tool.

o Formulas and functions: In Excel, you can use essential math functions easily to modify your
data through desired values, such as Addition, subtraction, multiplication, and division. However,
you should know that how to use these basic math functions in Excel.
o Autofill: This feature is useful when you want to the same equation across multiple fields or cells
without re-entering the information from scratch. If you do not use this function, you have to
retype the formula or need to drag the cursor from the cell's lower right corner until the cell you
want to fill up. Therefore, users can rely on this feature for the sake of efficiency through the data
manipulation process.
o Sort and Filter: When you are analyzing data and need to find specific data, you can save a lot of
time at that time by using the filtering options. It helps to isolate the information you wish to see.
o Removing duplicates: When you are collecting and assimilating data, there are often chances of
the same sets of information. In Excel, you can delete duplicate spreadsheet entries easily by
using the Delete Duplicate feature.
o Combining column: To paint a clear picture, you can merge columns or rows in Excel or use
other means to organize your data. Column splitting, merging, and merging-Columns or rows
offer users surety that the most relevant cells are immediately visible.

Difference between Data manipulation and Data modification


Both terms, data manipulation and data modification sound similar; however, they are not
interchangeable. Generally, data manipulation is the act of organizing data to make it cooler to read or
additional refined. On the other hand, data modification is the process of changing the existing data
values or data itself.

Anyone can get confused by their sound; therefore, here is an instance to explain both terms. Let's take
value X=7. It can be represented by data manipulation as X=3+4, or X=2+5, X=8-1, etc. By using data
manipulation, it can be represented as X=5.
Deployment & Application Enhancement
Java 8 Features
Oracle released a new version of Java as Java 8 in March 18, 2014. It was a revolutionary release of the
Java for software development platform. It includes various upgrades to the Java programming, JVM,
Tools and libraries.

Java 8 Programming Language Enhancements


Java 8 provides following features for Java Programming:

o Lambda expressions,
o Method references,
o Functional interfaces,
o Stream API,
o Default methods,
o Base64 Encode Decode,
o Static methods in interface,
o Optional class,
o Collectors class,
o ForEach() method,
o Nashorn JavaScript Engine,
o Parallel Array Sorting,
o Type and Repating Annotations,
o IO Enhancements,
o Concurrency Enhancements,
o JDBC Enhancements etc.

Lambda Expressions
Lambda expression helps us to write our code in functional style. It provides a clear and concise way to
implement SAM interface(Single Abstract Method) by using an expression. It is very useful in collection
library in which it helps to iterate, filter and extract data.

20.2M

466
OOPs Concepts in Java

Method References
Java 8 Method reference is used to refer method of functional interface . It is compact and easy form of
lambda expression. Each time when you are using lambda expression to just referring a method, you can
replace your lambda expression with method reference.

Functional Interface
An Interface that contains only one abstract method is known as functional interface. It can have any
number of default and static methods. It can also declare methods of object class.

Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).

Optional
Java introduced a new class Optional in Java 8. It is a public final class which is used to deal with
NullPointerException in Java application. We must import java.util package to use this class. It provides
methods to check the presence of value for particular variable.

forEach
Java provides a new method forEach() to iterate the elements. It is defined in Iterable and Stream
interfaces.

It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface
can use forEach() method to iterate elements.

This method takes a single parameter which is a functional interface. So, you can pass lambda expression
as an argument.

Date/Time API
Java has introduced a new Date and Time API since Java 8. The java.time package contains Java 8 Date
and Time classes.

Default Methods
Java provides a facility to create default methods inside the interface. Methods which are defined inside
the interface and tagged with default keyword are known as default methods. These methods are non-
abstract methods and can have method body.
Nashorn JavaScript Engine
Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual
Machine). Java provides a command-line tool jjs which is used to execute JavaScript code.

You can execute JavaScript code by two ways:

1. Using jjs command-line tool, and


2. By embedding into Java source code.

StringJoiner
Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of
characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,),
hyphen(-) etc.

Collectors
Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating
elements into collections, summarizing elements according to various criteria etc.

Stream API
Java 8 java.util.stream package consists of classes, interfaces and an enum to allow functional-style
operations on the elements. It performs lazy computation. So, it executes only when it requires.

Stream Filter
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose,
you want to get only even elements of your list, you can do this easily with the help of filter() method.

This method takes predicate as an argument and returns a stream of resulted elements.

Java Base64 Encoding and Decoding


Java provides a class Base64 to deal with encryption and decryption. You need to import java.util.Base64
class in your source file to use its methods.

This class provides three different encoders and decoders to encrypt information at each level.

Java Parallel Array Sorting


Java provides a new additional feature in Arrays class which is used to sort array elements parallelly. The
parallelSort() method has added to java.util.Arrays class that uses the JSR 166 Fork/Join parallelism
common pool to provide sorting of arrays. It is an overloaded method.

Java 8 Security Enhancements


1) The Java Secure Socket Extension(JSSE) provider enables the protocols Transport Layer Security (TLS)
1.1 and TLS 1.2 by default on the client side.

2) A improved method AccessController.doPrivileged has been added which enables code to assert a
subset of its privileges, without preventing the full traversal of the stack to check for other permissions.

3) Advanced Encryption Standard (AES) and Password-Based Encryption (PBE) algorithms, such as
PBEWithSHA256AndAES_128 and PBEWithSHA512AndAES_256 has been added to the SunJCE provider.

4) Java Secure Socket Extension (SunJSSE) has enabled Server Name Indication (SNI) extension for client
applications by default in JDK 7 and JDK 8 supports the SNI extension for server applications. The SNI
extension is a feature that extends the SSL/TLS protocols to indicate what server name the client is
attempting to connect to during handshaking.

5) The SunJSSE is enhanced to support Authenticated Encryption with Associated Data (AEAD) algorithms.
The Java Cryptography Extension (SunJCE) provider is enhanced to support AES/GCM/NoPadding cipher
implementation as well as Galois/Counter Mode (GCM) algorithm parameters.

6) A new command flag -importpassword is added to the keytool utility. It is used to accept a password
and store it securely as a secret key. Classes such as java.security.DomainLoadStoreParameter
andjava.security.PKCS12Attribute is added to support DKS keystore type.

7) In JDK 8, the cryptographic algorithms have been enhanced with the SHA-224 variant of the SHA-2
family of message-digest implementations.

8) Enhanced support for NSA Suite B Cryptography which includes:

o OID registration for NSA Suite B cryptography algorithms


o Support for 2048-bit DSA key pair generation and additional signature algorithms for 2048-bit
DSA keys such as SHA224withDSA and SHA256withDSA.
o Lifting of the keysize restriction from 1024 to 2048 for Diffie-Hellman (DH) algorithm.

9) SecureRandom class provides the generation of cryptographically strong random numbers which is
used for private or public keys, ciphers and signed messages. The getInstanceStrong() method was
introduced in JDK 8, which returns an instance of the strongest SecureRandom. It should be used when
you need to create RSA private and public key. SecureRandom includes following other changes:

o Two new implementations has introduced for UNIX platforms, which provide blocking and non-
blocking behavior.
10) A new PKIXRevocationChecker class is included which checks the revocation status of certificates with
the PKIX algorithm. It supports best effort checking, end-entity certificate checking, and mechanism-
specific options.

11) The Public Key Cryptography Standards 11 (PKCS) has been expanded to include 64-bit supports for
Windows.

12) Two new rcache types are added to Kerberos 5. Type none means no rcache at all, and type dfl means
the DFL style file-based rcache. Also, the acceptor requested subkey is now supported. They are
configured using the sun.security.krb5.rcache and sun.security.krb5.acceptor.subkey system properties.

13) In JDK 8, Kerberos 5 protocol transition and constrained delegation are supported within the same
realm.

14) Java 8 has disabled weak encryption by default. The DES-related Kerberos 5 encryption types are not
supported by default. These encryption types can be enabled by adding allow_weak_crypto=true in the
krb5.conf file.

15) You can set server name to null to denote an unbound server. It means a client can request for the
service using any server name. After a context is established, the server can retrieve the name as a
negotiated property with the key name SASL.BOUND_SERVER_NAME.

16) Java Native Interface (JNI) bridge to native Java Generic Security Service (JGSS) is now supported on
Mac OS X. You can set system property sun.security.jgss.native to true to enable it.

17) A new system property, jdk.tls.ephemeralDHKeySize is defined to customize the ephemeral DH key
sizes. The minimum acceptable DH key size is 1024 bits, except for exportable cipher suites or legacy
mode (jdk.tls.ephemeralDHKeySize=legacy).

18) Java Secure Socket Extension (JSSE) provider honors the client's cipher suite preference by default.
However, the behavior can be changed to respect the server's cipher suite preference by calling
SSLParameters.setUseCipherSuitesOrder(true) over the server.

Java 8 Tools Enhancements


1) A jjs command is introduced, which invokes the Nashorn engine either in interactive shell mode, or to
interpret script files.

2) The java command is capable of launching JavaFX applications, provided that the JavaFX application is
packaged correctly.

3) The java command man page (both nroff and HTML) has been completely reworked. The advanced
options are now divided into Runtime, Compiler, Garbage Collection, and Serviceability, according to the
area that they affect. Several previously missing options are now described. There is also a section for
options that were deprecated or removed since the previous release.
4) New jdeps command-line tool allows the developer to analyze class files to determine package-level or
class-level dependencies.

5) You can access diagnostic commands remotely, which were previously accessible only locally via the
jcmd tool. Remote access is provided using the Java Management Extensions (JMX), so diagnostic
commands are exposed to a platform MBean registered to the platform MBean server. The MBean is the
com.sun.management.DiagnosticCommandMBean interface.

6) A new option -tsapolicyid is included in the jarsigner tool which enables you to request a signed time
stamp from a Time Stamping Authority and attach it to a signed JAR file.

7) A new method java.lang.reflect.Executable.getParameters is included which allows you to access the


names of the formal parameters of any method or constructor. However, .class files do not store formal
parameter names by default. To store formal parameter names in a particular .class file, and thus enable
the Reflection API to retrieve formal parameter names, compile the source file with the -parameters
option of the javac compiler.

8) The type rules for binary comparisons in the Java Language Specification (JLS) Section 15.21 will now be
correctly enforced by javac.

9) In this release, the apt tool and its associated API contained in the package com.sun.mirror have been
removed.

Javadoc Enhancements
In Java SE 8, the following new APIs were added to the Javadoc tool.

o A new DocTree API introduce a scanner which enables you to traverse source code that is
represented by an abstract syntax tree. This extends the Compiler Tree API to provide structured
access to the content of javadoc comments.
o The javax.tools package contains classes and interfaces that enable you to invoke the Javadoc tool
directly from a Java application, without executing a new process.
o The "Method Summary" section of the generated documentation of a class or interface has been
restructured. Method descriptions in this section are grouped by type. By default, all methods are
listed. You can click a tab to view methods of a particular type (static, instance, abstract, concrete,
or deprecated, if they exist in the class or interface).
o The javadoc tool now has support for checking the content of javadoc comments for issues that
could lead to various problems, such as invalid HTML or accessibility issues, in the files that are
generated by javadoc. The feature is enabled by default, and can also be controlled by the new -
Xdoclint option.

Pack200 Enhancements
The Java class file format has been updated because of JSR 292 which Supports Dynamically Typed
Languages on the Java Platform.

The Pack200 engine has been updated to ensure that Java SE 8 class files are compressed effectively.
Now, it can recognize constant pool entries and new bytecodes introduced by JSR 292. As a result,
compressed files created with this version of the pack200 tool will not be compatible with older versions
of the unpack200 tool.

Java 8 I/O Enhancements


In Java 8, there are several improvements to the java.nio.charset.Charset and extended charset
implementations. It includes the following:

o A New SelectorProvider which may improve performance or scalability for server. The /dev/poll
SelectorProvider continues to be the default. To use the Solaris event port mechanism, run with
the system property java.nio.channels.spi.Selector set to the value
sun.nio.ch.EventPortSelectorProvider.
o The size of <JDK_HOME>/jre/lib/charsets.jar file is decreased.
o Performance has been improvement for the java.lang.String(byte[], ∗) constructor and the
java.lang.String.getBytes() method.

Java 8 Networking Enhancements


1) A new class java.net.URLPermission has been added. It represents a permission for accessing a resource
defined by a given URL.

2) A package jdk.net has been added which contains platform specific socket options and a mechanism
for setting these options on all of the standard socket types. The socket options are defined in
jdk.net.ExtendedSocketOptions.

3) In class HttpURLConnection, if a security manager is installed, and if a method is called which results in
an attempt to open a connection, the caller must possess either a "connect"SocketPermission to the
host/port combination of the destination URL or a URLPermission that permits this request.

If automatic redirection is enabled, and this request is redirected to another destination, the caller must
also have permission to connect to the redirected host/URL.

Java 8 Concurrency Enhancements


The java.util.concurrent package added two new interfaces and four new classes.

Java.util.concurrent Interfaces
Interface Description

public static interface It is a marker interface which is used to


CompletableFuture.AsynchronousCompletionTask identify asynchronous tasks produced by
async methods. It may be useful for
monitoring, debugging, and tracking
asynchronous activities.

public interface CompletionStage<T> It creates a stage of a possibly asynchronous


computation, that performs an action or
computes a value when another
CompletionStage completes.

Java.util.concurrent Classes

Class Description

public class CompletableFuture<T> extends Object It is aFuture that may be explicitly completed,
implements Future<T>, CompletionStage<T> and may be used as a CompletionStage,
supporting dependent functions and actions
that trigger upon its completion.

public static class It is a view of a ConcurrentHashMap as a Set of


ConcurrentHashMap.KeySetView<K,V> extends keys, in which additions may optionally be
Object implements Set<K>, Serializable enabled by mapping to a common value.

public abstract class CountedCompleter<T> A ForkJoinTask with a completion action


extends ForkJoinTask<T> performed when triggered and there are no
remaining pending actions.

public class CompletionException extends It throws an exception when an error or other


RuntimeException exception is encountered in the course of
completing a result or task.

New Methods in java.util.concurrent.ConcurrentHashMap class


ConcurrentHashMap class introduces several new methods in its latest release. It includes various forEach
methods (forEach, forEachKey, forEachValue, and forEachEntry), search methods (search, searchKeys,
searchValues, and searchEntries) and a large number of reduction methods (reduce, reduceToDouble,
reduceToLong etc.). Other miscellaneous methods (mappingCount and newKeySet) have been added as
well.

New classes in java.util.concurrent.atomic

Latest release introduces scalable, updatable, variable support through a small set of new classes
DoubleAccumulator, DoubleAdder, LongAccumulator andLongAdder. It internally employ contention-
reduction techniques that provide huge throughput improvements as compared to Atomic variables.

Class Description

public class DoubleAccumulator extends It is used for one or more variables that together
Number implements Serializable maintain a running double value updated using a
supplied function.

public class DoubleAdder extends Number It is used for one or more variables that together
implements Serializable maintain an initially zero double sum.

public class LongAccumulator extends It is used for one or more variables that together
Number implements Serializable maintain a running long value updated using a supplied
function.

public class LongAdder extends Number It is used for one or more variables that together
implements Serializable maintain an initially zero long sum.

New methods in java.util.concurrent.ForkJoinPool Class


This class has added two new methods getCommonPoolParallelism() and commonPool(), which return the
targeted parallelism level of the common pool, or the common pool instance, respectively.

Method Description

public static ForkJoinPool commonPool() It returns the common pool instance.

Public static int It returns the targeted parallelism level of the common
getCommonPoolParallelism() pool.

New class java.util.concurrent.locks.StampedLock


A new class StampedLock is added which is used to add capability-based lock with three modes for
controlling read/write access (writing, reading, and optimistic reading). This class also supports methods
that conditionally provide conversions across the three modes.

Class Description

public class StampedLock extends Object This class represents a capability-based lock with three
implements Serializable modes for controlling read/write access.

Java API for XML Processing (JAXP) 1.6 Enhancements


In Java 8, Java API is added for XML Processing (JAXP) 1.6. It requires the use of the service provider
loader facility which is defined by java.util.ServiceLoader to load services from service configuration files.

The rationale for this is to allow for future modularization of the Java SE platform where service providers
may be deployed by means other than JAR files and perhaps without the service configuration files.

Java Virtual Machine Enhancements


The verification of invokespecial instructions has been tightened so that only an instance initialization
method in the current class or its direct super class may be invoked.

Java Mission Control 5.3 is included in Java 8


Java Mission Control (JMC) is an advanced set of tools that enables efficient and detailed data analysis
and delivers advanced, unobtrusive Java monitoring and management. JMC provides sections for
common analysis areas such as code performance, memory and latency.

Babel Language Packs in Japanese and Simplified Chinese are now included by default in the Java Mission
Control that is included in the JDK 8.

Java 8 Internationalization Enhancements


1) Unicode Enhancements

The JDK 8 includes support for Unicode 6.2.0. It contains the following features.

o 733 new characters including Turkish Lira sign.

o 7 new scripts:
o Meroitic Hieroglyphs
o Meroitic Cursive
o Sora Sompeng
o Chakma
o Sharada
o Takri
o Miao

o 11 new blocks: including 7 blocks for the new scripts listed above and 4 blocks for the following
existing scripts:
o Arabic Extended-A
o Sundanese Supplement
o Meetei Mayek Extensions
o Arabic Mathematical Alphabetical Symbols

Adoption of Unicode CLDR Data and the java.locale.providers


System Property
The Unicode Consortium has released the Common Locale Data Repository (CLDR) project to "support the
world's languages, with the largest and most extensive standard repository of locale data available." The
CLDR is becoming the de-facto standard for locale data. The CLDR's XML-based locale data has been
incorporated into the JDK 8 release, however it is disabled by default.

There are four distinct sources for locale data:

o CLDR represents the locale data provided by the Unicode CLDR project.
o HOST represents the current user's customization of the underlying operating system's settings. It
works only with the user's default locale, and the customizable settings may vary depending on
the OS, but primarily Date, Time, Number, and Currency formats are supported.
o SPI represents the locale sensitive services implemented in the installed SPI providers.
o JRE represents the locale data that is compatible with the prior JRE releases.
To select the desired locale data source, use the java.locale.providers system property. listing the data
sources in the preferred order. For example: java.locale.providers=HOST,SPI,CLDR,JRE The default
behavior is equivalent to the following setting: java.locale.providers=JRE,SPI

Java 8 New Calendar and Locale APIs


The JDK 8 includes two new classes, several new methods, and a new return value for an existing static
method.

Two new abstract classes for service providers are added to the java.util.spi package.

Class Description

public abstract class CalendarDataProvider It is an abstract class for service providers that provide
extends LocaleServiceProvider locale-dependent Calendar parameters.

public abstract class It is an abstract class for service providers that provide
CalendarNameProvider extends localized string representations (display names) of
LocaleServiceProvider Calendar field values.

A static method is now able to recognize Locale.UNICODE_LOCALE_EXTENSION for the numbering


system.

Method Description

public static final It is used to get the DecimalFormatSymbols instance for the specified
DecimalFormatSymbols locale. This method provides access to DecimalFormatSymbols
getInstance(Locale locale) instances for locales supported by the Java runtime itself as well as for
those supported by installed DecimalFormatSymbolsProvider
implementations. It throws NullPointerException if locale is null.

Added New methods in calender API:

Method Description

public boolean It returns true if the given locale is supported by this locale service
isSupportedLocale(Locale provider. The given locale may contain extensions that should be
locale) taken into account for the support determination. It is define in
java.util.spi.LocaleServiceProvider class

public String It returns the calendar type of this Calendar. Calendar types are
getCalendarType() defined by the Unicode Locale Data Markup Language (LDML)
specification. It is defined in java.util.Calendar class.

New style specifiers are added for the Calendar.getDisplayName and Calendar.getDisplayNames methods
to determine the format of the Calendar name.

Specifier Description

public static final int It is a style specifier for getDisplayName and getDisplayNames
SHORT_FORMAT indicating a short name used for format.

public static final int It is a style specifier for getDisplayName and getDisplayNames
LONG_FORMAT indicating a long name used for format.

public static final int It is a style specifier for getDisplayName and getDisplayNames
SHORT_STANDALONE indicating a short name used independently, such as a month
abbreviation as calendar headers.

public static final int It is a style specifier for getDisplayName and getDisplayNames
LONG_STANDALONE indicating a long name used independently, such as a month name as
calendar headers.

Two new Locale methods for dealing with a locale's (optional) extensions.

Method Description

public boolean It returns true if this Locale has any extensions.


hasExtensions()

public Locale It returns a copy of this Locale with no extensions. If this Locale has no
stripExtensions() extensions, this Locale is returned itself.
Two new Locale.filter methods return a list of Locale instances that match the specified criteria, as defined
in RFC 4647:

Method Description

public static List<Locale> It returns a list of matching Locale instances using the
filter(List<Locale.LanguageRange> filtering mechanism defined in RFC 4647. This is equivalent
priorityList,Collection<Locale> locales) to filter(List, Collection, FilteringMode) when mode is
Locale.FilteringMode.AUTOSELECT_FILTERING.

public static List<Locale> It returns a list of matching Locale instances using the
filter(List<Locale.LanguageRange> filtering mechanism defined in RFC 4647.
priorityList,Collection<Locale> locales,
Locale.FilteringMode mode)

Two new Locale.filterTags methods return a list of language tags that match the specified criteria, as
defined in RFC 4647.

Method Description

public static List<String> It returns a list of matching languages tags using the
filterTags(List<Locale.LanguageRange> basic filtering mechanism defined in RFC 4647. This is
priorityList, Collection<String> tags) equivalent to filterTags(List, Collection, FilteringMode)
when mode is
Locale.FilteringMode.AUTOSELECT_FILTERING.

public static List<String> It returns a list of matching languages tags using the
filterTags(List<Locale.LanguageRange> basic filtering mechanism defined in RFC 4647.
priorityList, Collection<String> tags,
Locale.FilteringMode mode)

Two new lookup methods return the best-matching locale or language tag using the lookup mechanism
defined in RFC 4647.

Method Description

public static Locale lookup(List<Locale.LanguageRange> It returns a Locale instance for the best-
priorityList, Collection<Locale> locales) matching language tag using the lookup
mechanism defined in RFC 4647.

Public static String It returns the best-matching language tag


lookupTag(List<Locale.LanguageRange> using the lookup mechanism defined in
priorityList,Collection<String> tags) RFC 4647.

Other Java 8 Version Enhancements

Enhancements in JDK 8u5

1) The frequency in which the security prompts are shown for an application has been reduced.

Enhancements in JDK 8u11

1) An option to suppress offers from sponsors when the JRE is installed or updated is available in the
Advanced tab of the Java Control Panel.

2) The Entry-Point attribute can be included in the JAR file manifest to identify one or more classes as a
valid entry point for your RIA(Rich Internet application).

Enhancements in JDK 8u20

1) The javafxpackager tool has been renamed to javapackager. This tool has been enhanced with new
arguments for self-contained application bundlers.

Follwing enhancements are related to the java tool:

o An experimental JIT compiler option related to Restricted Transactional Memory (RTM) has been
added.
o Several options related to string deduplication have been added.
o Several options related to Advanced Encryption Standard (AES) intrinsics have been added.
o Combinations of garbage collection options have been deprecated.

2) Garbage Collection Tuning Guide has been added to the Java HotSpot Virtual Machine. It describes the
garbage collectors included with the Java HotSpot VM and helps you to decide which garbage collector
can best optimize the performance of your application, especially if it handles large amounts of data
(multiple gigabytes), has many threads, and has high transaction rates.

Enhancements in JDK 8u31


1) In this release, the SSLv3 protocol is removed from the Java Control Panel Advanced options.

Enhancements in JDK 8u40

Java tool

1) The -XX:+CheckEndorsedAndExtDirs has been added because the endorsed-standards override


mechanism (JDK-8065675) and the extension mechanism (JDK-8065702) have been deprecated. The
option helps identify any existing uses of these mechanisms and is supported in JDK 7u80 and JDK 8u40.

2) Java Flight Recorder (JFR) offers a variety of ways to unlock commercial features and enable JFR during
the runtime of an application.

It includes java command line options such as jcmd diagnostic commands and Graphical User Interface
(GUI) controls within Java Mission Control. This flexibility enables you to provide the appropriate options
at startup, or interact with JFR later.

3) The option -XX:StartFlightRecording=parameter=value has a new parameter, dumponexit={true|false},


which specifies whether a dump file of JFR data should be generated when the JVM terminates in a
controlled manner.

4) The options related to Restricted Transactional Memory (RTM) are no longer experimental. These
options include -XX:RTMAbortRatio=abort_ratio, -XX:RTMRetryCount=number_of_retries, -XX:
+UseRTMDeopt, and -XX:+UseRTMLocking.

5) In Java 8, Application Class Data Sharing (AppCDS) has been introduced. AppCDS extends CDS (Class
Data Sharing) to enable classes from the standard extensions directories and the application class path to
be placed in the shared archive. This is a commercial feature and is no longer considered experimental.

6) New options -XX:+ResourceManagement and -XX:ResourceManagementSampleInterval=value have


been added.

7) Additional information about large pages has been added. Large Pages, also known as huge pages, are
memory pages that are significantly larger than the standard memory page size. Large pages optimize
processor Translation-Lookaside Buffers. The Linux options -XX:+UseHugeTLBFS, -XX:+UseSHM, and -XX:
+UseTransparentHugePages have been documented.

8) The option -XX:ObjectAlignmentInBytes=alignment has been documented.

JJS tool

1) The option --optimistic-types=[true|false] has been added. It enables or disables optimistic type
assumptions with deoptimizing recompilation.

2) The option --language=[es5] has been added to the jjs tool. It specifies the ECMAScript language
version.
Javapackager tool

1) New arguments are available for OS X bundlers. The mac.CFBundleVersion argument identifies the
internal version number to be used.

2) The mac.dmg.simple argument indicates if DMG customization steps that depend on executing
AppleScript code are skipped.

Jcmd tool

Jcmd tool is used to dynamically interact with Java Flight Recorder (JFR). You can use it to unlock
commercial features, enable/start/stop flight recordings, and obtain various status messages from the
system.

Jstat tool

The jstat tool has been updated with information about compressed class space which is a special part of
metaspace.

Virtual machine

The Scalable Native Memory Tracking HotSpot VM feature helps diagnose VM memory leaks and clarify
users when memory leaks are not in the VM. Native Memory Tracker can be run without self-shutdown on
large systems and without causing a significant performance impact beyond what is considered
acceptable for small programs.

Lambda Expressions
Java Lambda Expressions
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a
clear and concise way to represent one method interface using an expression. It is very useful in collection
library. It helps to iterate, filter and extract data from collection.

The Lambda expression is used to provide the implementation of an interface which has functional
interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again
for providing the implementation. Here, we just write the implementation code.

Java lambda expression is treated as a function, so compiler does not create .class file.

Functional Interface
Lambda expression provides implementation of functional interface. An interface which has only one
abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is
used to declare an interface as functional interface.Java Program for Beginne

Why use Lambda Expression


1. To provide the implementation of Functional interface.
2. Less coding.

Java Lambda Expression Syntax


(argument-list) -> {body}  

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

No Parameter Syntax

1. () -> {  
2. //Body of no parameter lambda  
3. }  

One Parameter Syntax

1. (p1) -> {  
2. //Body of single parameter lambda  
3. }  

Two Parameter Syntax

1. (p1,p2) -> {  
2. //Body of multiple parameter lambda  
3. }  

Let's see a scenario where we are not implementing Java lambda expression. Here, we are implementing
an interface without using lambda expression.

Without Lambda Expression


1. interface Drawable{  
2.     public void draw();  
3. }  
4. public class LambdaExpressionExample {  
5.     public static void main(String[] args) {  
6.         int width=10;  
7.   
8.         //without lambda, Drawable implementation using anonymous class  
9.         Drawable d=new Drawable(){  
10.             public void draw(){System.out.println("Drawing "+width);}  
11.         };  
12.         d.draw();  
13.     }  
14. }  

Output:

Drawing 10

Java Lambda Expression Example


Now, we are going to implement the above example with the help of Java lambda expression.

1. @FunctionalInterface  //It is optional  
2. interface Drawable{  
3.     public void draw();  
4. }  
5.   
6. public class LambdaExpressionExample2 {  
7.     public static void main(String[] args) {  
8.         int width=10;  
9.           
10.         //with lambda  
11.         Drawable d2=()->{  
12.             System.out.println("Drawing "+width);  
13.         };  
14.         d2.draw();  
15.     }  
16. }  

Output:
Drawing 10

A lambda expression can have zero or any number of arguments. Let's see the examples:

Java Lambda Expression Example: No Parameter


1. interface Sayable{  
2.     public String say();  
3. }  
4. public class LambdaExpressionExample3{  
5. public static void main(String[] args) {  
6.     Sayable s=()->{  
7.         return "I have nothing to say.";  
8.     };  
9.     System.out.println(s.say());  
10. }  
11. }  

Output:

I have nothing to say.

Java Lambda Expression Example: Single Parameter


1. interface Sayable{  
2.     public String say(String name);  
3. }  
4.   
5. public class LambdaExpressionExample4{  
6.     public static void main(String[] args) {  
7.       
8.         // Lambda expression with single parameter.  
9.         Sayable s1=(name)->{  
10.             return "Hello, "+name;  
11.         };  
12.         System.out.println(s1.say("Sonoo"));  
13.           
14.         // You can omit function parentheses    
15.         Sayable s2= name ->{  
16.             return "Hello, "+name;  
17.         };  
18.         System.out.println(s2.say("hcl"));  
19.     }  
20. }  

Output:

Hello, Sonoo
Hello, hcl

Java Lambda Expression Example: Multiple Parameters


1. interface Addable{  
2.     int add(int a,int b);  
3. }  
4.   
5. public class LambdaExpressionExample5{  
6.     public static void main(String[] args) {  
7.           
8.         // Multiple parameters in lambda expression  
9.         Addable ad1=(a,b)->(a+b);  
10.         System.out.println(ad1.add(10,20));  
11.           
12.         // Multiple parameters with data type in lambda expression  
13.         Addable ad2=(int a,int b)->(a+b);  
14.         System.out.println(ad2.add(100,200));  
15.     }  
16. }  

Output:

30
300

Java Lambda Expression Example: with or without return


keyword
In Java lambda expression, if there is only one statement, you may or may not use return keyword. You
must use return keyword when lambda expression contains multiple statements.

1. interface Addable{  
2.     int add(int a,int b);  
3. }  
4.   
5. public class LambdaExpressionExample6 {  
6.     public static void main(String[] args) {  
7.           
8.         // Lambda expression without return keyword.  
9.         Addable ad1=(a,b)->(a+b);  
10.         System.out.println(ad1.add(10,20));  
11.           
12.         // Lambda expression with return keyword.    
13.         Addable ad2=(int a,int b)->{  
14.                             return (a+b);   
15.                             };  
16.         System.out.println(ad2.add(100,200));  
17.     }  
18. }  

Output:

30
300

Java Lambda Expression Example: Foreach Loop


1. import java.util.*;  
2. public class LambdaExpressionExample7{  
3.     public static void main(String[] args) {  
4.           
5.         List<String> list=new ArrayList<String>();  
6.         list.add("ankit");  
7.         list.add("mayank");  
8.         list.add("irfan");  
9.         list.add("jai");  
10.           
11.         list.forEach(  
12.             (n)->System.out.println(n)  
13.         );  
14.     }  
15. }  

Output:
ankit
mayank
irfan
jai

Java Lambda Expression Example: Multiple Statements


1. @FunctionalInterface  
2. interface Sayable{  
3.     String say(String message);  
4. }  
5.   
6. public class LambdaExpressionExample8{  
7.     public static void main(String[] args) {  
8.       
9.         // You can pass multiple statements in lambda expression  
10.         Sayable person = (message)-> {  
11.             String str1 = "I would like to say, ";  
12.             String str2 = str1 + message;   
13.             return str2;  
14.         };  
15.             System.out.println(person.say("time is precious."));  
16.     }  
17. }  

Output:

I would like to say, time is precious.

Java Lambda Expression Example: Creating Thread


You can use lambda expression to run thread. In the following example, we are implementing run method
by using lambda expression.

1. public class LambdaExpressionExample9{  
2.     public static void main(String[] args) {  
3.       
4.         //Thread Example without lambda  
5.         Runnable r1=new Runnable(){  
6.             public void run(){  
7.                 System.out.println("Thread1 is running...");  
8.             }  
9.         };  
10.         Thread t1=new Thread(r1);  
11.         t1.start();  
12.         //Thread Example with lambda  
13.         Runnable r2=()->{  
14.                 System.out.println("Thread2 is running...");  
15.         };  
16.         Thread t2=new Thread(r2);  
17.         t2.start();  
18.     }  
19. }  

Output:

Thread1 is running...
Thread2 is running...

Java lambda expression can be used in the collection framework. It provides efficient and concise way to
iterate, filter and fetch data. Following are some lambda and collection examples provided.

Java Lambda Expression Example: Comparator


1. import java.util.ArrayList;  
2. import java.util.Collections;  
3. import java.util.List;  
4. class Product{  
5.     int id;  
6.     String name;  
7.     float price;  
8.     public Product(int id, String name, float price) {  
9.         super();  
10.         this.id = id;  
11.         this.name = name;  
12.         this.price = price;  
13.     }  
14. }  
15. public class LambdaExpressionExample10{  
16.     public static void main(String[] args) {  
17.         List<Product> list=new ArrayList<Product>();  
18.           
19.         //Adding Products  
20.         list.add(new Product(1,"HP Laptop",25000f));  
21.         list.add(new Product(3,"Keyboard",300f));  
22.         list.add(new Product(2,"Dell Mouse",150f));  
23.           
24.         System.out.println("Sorting on the basis of name...");  
25.   
26.         // implementing lambda expression  
27.         Collections.sort(list,(p1,p2)->{  
28.         return p1.name.compareTo(p2.name);  
29.         });  
30.         for(Product p:list){  
31.             System.out.println(p.id+" "+p.name+" "+p.price);  
32.         }  
33.   
34.     }  
35. }  

Output:

Sorting on the basis of name...


2 Dell Mouse 150.0
1 HP Laptop 25000.0
3 Keyboard 300.0

Java Lambda Expression Example: Filter Collection Data


1. import java.util.ArrayList;  
2. import java.util.List;  
3. import java.util.stream.Stream;   
4. class Product{  
5.     int id;  
6.     String name;  
7.     float price;  
8.     public Product(int id, String name, float price) {  
9.         super();  
10.         this.id = id;  
11.         this.name = name;  
12.         this.price = price;  
13.     }  
14. }  
15. public class LambdaExpressionExample11{  
16.     public static void main(String[] args) {  
17.         List<Product> list=new ArrayList<Product>();  
18.         list.add(new Product(1,"Samsung A5",17000f));  
19.         list.add(new Product(3,"Iphone 6S",65000f));  
20.         list.add(new Product(2,"Sony Xperia",25000f));  
21.         list.add(new Product(4,"Nokia Lumia",15000f));  
22.         list.add(new Product(5,"Redmi4 ",26000f));  
23.         list.add(new Product(6,"Lenevo Vibe",19000f));  
24.           
25.         // using lambda to filter data  
26.         Stream<Product> filtered_data = list.stream().filter(p -> p.price > 20000);  
27.           
28.         // using lambda to iterate through collection  
29.         filtered_data.forEach(  
30.                 product -> System.out.println(product.name+": "+product.price)  
31.         );  
32.     }  
33. }  

Output:

Iphone 6S: 65000.0


Sony Xperia: 25000.0
Redmi4 : 26000.0

Java Lambda Expression Example: Event Listener


import javax.swing.JButton;  
1. import javax.swing.JFrame;  
2. import javax.swing.JTextField;  
3. public class LambdaEventListenerExample {  
4.     public static void main(String[] args) {  
5.         JTextField tf=new JTextField();  
6.         tf.setBounds(50, 50,150,20);  
7.         JButton b=new JButton("click");  
8.         b.setBounds(80,100,70,30);  
9.           
10.         // lambda expression implementing here.  
11.         b.addActionListener(e-> {tf.setText("hello swing");});  
12.           
13.         JFrame f=new JFrame();  
14.         f.add(tf);f.add(b);  
15.         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
16.         f.setLayout(null);  
17.         f.setSize(300, 200);  
18.         f.setVisible(true);  
19.   
20.     }  
21.   
22. }  

Output:

You might also like