0% found this document useful (0 votes)
8 views16 pages

Java Unit 3

Java 8, released on March 18, 2014, introduced significant features including lambda expressions, method references, and the forEach() method for enhanced programming capabilities. Lambda expressions allow for concise implementation of functional interfaces, while method references provide a shorthand for referring to methods. Additionally, Java 8 includes Base64 encoding/decoding and improvements to the Java Module System, which organizes code into modules for better application structure.

Uploaded by

Afjal Ansari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

Java Unit 3

Java 8, released on March 18, 2014, introduced significant features including lambda expressions, method references, and the forEach() method for enhanced programming capabilities. Lambda expressions allow for concise implementation of functional interfaces, while method references provide a shorthand for referring to methods. Additionally, Java 8 includes Base64 encoding/decoding and improvements to the Java Module System, which organizes code into modules for better application structure.

Uploaded by

Afjal Ansari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 provides following features for Java Programming:

o Lambda expressions,
o Method references,
o Functional interfaces,
o Default methods,
o Base64 Encode Decode,
o Static methods in interface,
o ForEach() method, etc

Java Lambda Expressions


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.

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 @
(argument-list) -> {body}, which is used to declare an interface as functional interface.

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

4. (p1) -> {
5. //Body of single parameter lambda
6. }

Two Parameter Syntax

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

Example 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(){[Link]("Drawing "+width);}
11. };
12. [Link]();
13. }
14. }
Lambda Expression Example
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. [Link]("Drawing "+width);
13. };
14. [Link]();
15. }
16. }

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. [Link]([Link]("Sonoo"));
13.
14. // You can omit function parentheses
15. Sayable s2= name ->{
16. return "Hello, "+name;
17. };
18. [Link]([Link]("Sonoo"));
19. }
20. }

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. [Link]([Link](10,20));
11.
12. // Multiple parameters with data type in lambda expression
13. Addable ad2=(int a,int b)->(a+b);
14. [Link]([Link](100,200));
15. }
16. }

Java Method References


Java provides a new feature called method reference in 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. In this tutorial, we are explaining method reference concept in detail.
Types of Method References
There are following types of method references in java:

1. Reference to a static method.


2. Reference to an instance method.
3. Reference to a constructor.

1) Reference to a Static Method


You can refer to static method defined in the class. Following is the syntax and example which
describe the process of referring static method in Java.

1. Syntax: - ContainingClass::staticMethodName

Example

1. interface Sayable{
2. void say();
3. }
4. public class MethodReference {
5. public static void saySomething(){
6. [Link]("Hello, this is static method.");
7. }
8. public static void main(String[] args) {
9. // Referring static method
10. Sayable sayable = MethodReference::saySomething;
11. // Calling interface method
12. [Link]();
13. }
14. }

2) Reference to an Instance Method


like static methods, you can refer instance methods also.

Sysntax:- containingObject::instanceMethodName
Example
1. interface Sayable{
2. void say();
3. }
4. public class InstanceMethodReference {
5. public void saySomething(){
6. [Link]("Hello, this is non-static method.");
7. }
8. public static void main(String[] args) {
9. InstanceMethodReference methodReference = new InstanceMethodReference(); // Creati
ng object
10. // Referring non-static method using reference
11. Sayable sayable = methodReference::saySomething;
12. // Calling interface method
13. [Link]();
14. // Referring non-static method using anonymous object
15. Sayable sayable2 = new InstanceMethodReference()::saySomething; // You can use anon
ymous object also
16. // Calling interface method
17. [Link]();
18. }
19. }

3) Reference to a Constructor
You can refer a constructor by using the new keyword.

1. interface Messageable{
2. Message getMessage(String msg);
3. }
4. class Message{
5. Message(String msg){
6. [Link](msg);
7. }
8. }
9. public class ConstructorReference {
10. public static void main(String[] args) {
11. Messageable hello = Message::new;
12. [Link]("Hello");
13. }
14. }

Java Base64 Encode and Decode


Java provides a class Base64 to deal with encryption. You can encrypt and decrypt your data by
using provided methods. You need to import [Link].Base64 in your source file to use its
methods.

This class provides three different encoders and decoders to encrypt information at each level.
You can use these methods at the following levels.

Basic Encoding and Decoding


It uses the Base64 alphabet specified by Java in RFC 4648 and RFC 2045 for encoding and
decoding operations. The encoder does not add any line separator character. The decoder
rejects data that contains characters outside the base64 alphabet

URL and Filename Encoding and Decoding


It uses the Base64 alphabet specified by Java in RFC 4648 for encoding and decoding
operations. The encoder does not add any line separator character. The decoder rejects data
that contains characters outside the base64 alphabet

MIME
It uses the Base64 alphabet as specified in RFC 2045 for encoding and decoding operations. The
encoded output must be represented in lines of no more than 76 characters each and uses a
carriage return '\r' followed immediately by a linefeed '\n' as the line separator. No line
separator is added to the end of the encoded output. All line separators or other characters not
found in the base64 alphabet table are ignored in decoding operation.

Example simple type


import [Link].Base64;
public class base1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

// Create a simple String


String samplepwd="mypwd@123";
//Encode into Base64 format
String
Base64format=[Link]().encodeToString([Link]());
// Print he string
[Link](Base64format);

// Decode String

String encodestring="bXlwd2RAMTIz";

// decoe into string format


byte[]actualpass=[Link]().decode(encodestring);
String finaldecodes=new String(actualpass);
[Link](finaldecodes);
}
}

Example of URL
import [Link].Base64;
public class base1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

[Link] encoder=[Link]();
//Encoding url
String
str=[Link]("[Link]
5171".getBytes());
[Link](str);

//Decoding URl
[Link] decoder=[Link]();
String str1=new String([Link](str));
[Link](str1);

Example of MIME
import [Link].Base64;
public class base1 {

public static void main(String[] args) {


[Link] encoder=[Link]();
String msg="\"Hello, \\nYou are informed regarding your inconsistency of work\";";
// Encoded
String str=[Link]([Link]());
[Link](str);

// Decoded MiME

[Link] decoder=[Link]();
String dstr=new String([Link](str));
[Link](dstr);

Java forEach loop

Java provides a new method forEach() to iterate the elements. It is defined in Iterable and
Stream interface. It is a default method defined in the Iterable interface. Collection classes
which extends Iterable interface can use forEach loop to iterate elements.

This method takes a single parameter which is a functional interface. So, you can pass lambda
expression as an argument.
1. import [Link];
2. import [Link];
3. public class ForEachExample {
4. public static void main(String[] args) {
5. List<String> gamesList = new ArrayList<String>();
6. [Link]("Football");
7. [Link]("Cricket");
8. [Link]("Chess");
9. [Link]("Hocky");
10. [Link]("------------Iterating by passing lambda expression--------------");
11. [Link](games -> [Link](games));
12.
13. }
14. }

Java Module System


Java Module System is a major change in Java 9 version. Java added this feature to collect Java packages
and code into a single unit called module

In earlier versions of Java, there was no concept of module to create modular Java applications,
that why size of application increased and difficult to move around. Even JDK itself was too
heavy in size, in Java 8, [Link] file size is around 64MB.

To deal with situation, Java 9 restructured JDK into set of modules so that we can use only
required module for our project.

Module is a collection of Java programs or softwares. To describe a module, a Java file module-
[Link] is required. This file also known as module descriptor and defines the following

o Module name
o What does it export
o What does it require

Creating Java module required the following steps.

o Create a directory structure


o Create a module declarator
o Java source code

Create a Directory Structure


To create module, it is recommended to follow given directory structure, it is same as reverse-
domain-pattern, we do to create packages / project-structure in Java

Src

[Link]

Com

Axis

[Link]

[Link]

Create a file [Link], inside this file, declare a module by using module identifier and
provide module name same as the directory name that contains it. In our case, our directory name is
[Link]

Java Source Code


Now, create a Java file to compile and execute module. In our example, we have
a [Link] file that contains the following code.

1. class Hello{
2. public static void main(String[] args){
3. [Link]("Hello from the Java module");
4. }
5. }
Save this file inside src/[Link]/com/Axis/ with [Link] name.

Compile Java Module


To compile the module use the following command.
1. javac -d mods --module-source-path src/ --module [Link]

Run Module
1. java --module-path mods/ --module [Link]/[Link]

Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java compiler
and JVM.

Types

@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.

Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.

1. lass Animal{
2. void eatSomething(){[Link]("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
7. void eatsomething(){[Link] [Link]("eating foods");}//should be eatSomething
8. }
9.
10. class TestAnnotation1{
11. public static void main(String args[]){
12. Animal a=new Dog();
13. [Link]();
14. }}

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

1. import [Link].*;
2. class TestAnnotation2{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5. ArrayList list=new ArrayList();
6. [Link]("sonoo");
7. [Link]("vimal");
8. [Link]("ratan");
9.
10. for(Object obj:list)
11. [Link](obj);
12.
13. }}

@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.

1. class A{
2. void m(){[Link]("hello m");}
3.
4. @Deprecated
5. void n(){[Link]("hello n");}
6. }
7.
8. class TestAnnotation3{
9. public static void main(String args[]){
10.
11. A a=new A();
12. a.n();
13. }}

Anonymous Inner Classes


Java 9 introduced a new feature that allows us to use diamond operator with anonymous
classes. Using the diamond with anonymous classes was not allowed in Java 7.

In Java 9, as long as the inferred type is denotable, we can use the diamond operator when we
create an anonymous inner class.

Data types that can be written in Java program like int, String etc are called denotable types.
Java 9 compiler is enough smart and now can infer type.

1. abstract class ABCD<T>{


2. abstract T show(T a, T b);
3. }
4. public class TypeInferExample {
5. public static void main(String[] args) {
6. ABCD<String> a = new ABCD<>() { // diamond operator is empty, compiler infer type
7. String show(String a, String b) {
8. return a+b;
9. }
10. };
11. String result = [Link]("Java","9");
12. [Link](result);
13. }
14. }
Local Variable Type Inference or LVTI in Java 10
Local Variable Type Inference is one of the most evident change to language available from Java
10 onwards. It allows to define a variable using var and without specifying the type of it. The
compiler infers the type of the variable using the value provided. This type inference is restricted
to local variables.

Example
import [Link];

public class Tester {


public static void main(String[] args) {
var names = [Link]("Julie", "Robert", "Chris", "Joseph");
for (var name : names) {
[Link](name);
}
[Link]("");
for (var i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
}
}

Switch expression on Java 17


Java 17 has come up with some cool features for the language, one of which is switch
expressions. Maybe someone wonders, – But, does the switch already exists in Java? and the
answer is yes, as a statement that only evaluates a data but does not return a value. That is the
difference, being an expression it can return values, also include patterns to the case

Example

static String formatterPatternSwitch(Object o) {


return switch (o) {
case Integer i -> [Link]("int %d", i);
case Long l -> [Link]("long %d", l);
case Double d -> [Link]("double %f", d);
case String s -> [Link]("String %s", s);
default -> [Link]();
};
}

Text Blocks
A text block is an alternative form of Java string representation that can be used
anywhere a traditional double-quoted string literal can be used. Text blocks begin
with a “”” (3 double-quote marks) observed through non-obligatory whitespaces
and a newline. For example:

String text1 = "Axis college For Engineering";

// Using a text block


String text2 = """
Axis college For Engineering """;

Java Sealed Class


Java 15 introduced the concept of sealed classes. It is a preview feature. Java sealed classes and
interfaces restrict that which classes and interfaces may extend or implement them.

In other words, we can say that the class that cannot be inherited but can be instantiated is
known as the sealed class. It allows classes and interfaces to have more control over their
permitted subtypes. It is useful both for general domain modeling and for building a more
secure platform for libraries.

1. public sealed class Fruits permits Mango, Pineapple


2. {
3. int getCost();
4. default int getQuantity()
5. {
6. return 5;
7. }
8. }

You might also like