0% found this document useful (0 votes)
20 views

JAVA Module 5

java notes

Uploaded by

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

JAVA Module 5

java notes

Uploaded by

Swaraj Farakate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Worldline Level 2 Training on

Java
Module 5

Prof. Farendrakumar Ghodichor


SIT Lonavala

07/02/2024 1
Module 5: Java 8 Features

• Base 64 encoding/decoding
• Default and static methods in
Interfaces
• Functional Interfaces and Lambda
Expressions
• Streams

07/02/2024 2
1. 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 java.util.Base64 in your source file to use
its methods.

• This class provides three different encoders and decoders to


encrypt information at each level.
• 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
07/02/2024
alphabet. 3
Java Base64 Encode and
Decode
• 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.
07/02/2024 4
Nested Classes of Base64

• Base64.Decoder:
• This class implements a decoder for decoding byte data
using the Base64 encoding scheme as specified in RFC
4648 and RFC 2045.

• Base64.Encoder:
• This class implements an encoder for encoding byte data
using the Base64 encoding scheme as specified in RFC
4648 and RFC 2045.

07/02/2024 5
Base64 Methods
• public static Base64.Decoder getDecoder()
• public static Base64.Encoder getEncoder()
• public static Base64.Decoder getUrlDecoder()
• public static Base64.Encoder getUrlEncoder()
• public static Base64.Decoder getMimeDecoder()
• public static Base64.Encoder getMimeEncoder()

07/02/2024 6
Java Base64 Example: URL Encoding and Decoding
• import java.util.Base64;
• public class Base64BasicEncryptionExample {
• public static void main(String[] args) {
• // Getting encoder
• Base64.Encoder encoder = Base64.getUrlEncoder();
• // Encoding URL
• String eStr = encoder.encodeToString("http://www.sinhgad.edu".getBytes());
• System.out.println("Encoded URL: "+eStr);
• // Getting decoder
• Base64.Decoder decoder = Base64.getUrlDecoder();
• // Decoding URL
• String dStr = new String(decoder.decode(eStr));
• System.out.println("Decoded URL: "+dStr);
• } }
• Output:
• Encoded URL: aHR0cDovqYXZhLXR1dG9yaWFsLw==
• Decoded URL: http://www.sinhgad.edu
07/02/2024 7
2. Default and static methods in
Interfaces
• Java provides a facility to create default methods
inside the interface. Methods which are defined inside
the interface and tagged with default are known as
default methods. These methods are non-abstract
methods.

• You can also define static methods inside the


interface. Static methods are used to define utility
methods.
07/02/2024 8
• Example:
• interface Sayable{
• // default method
• default void say(){
• System.out.println("Hello, this is default method");
• }
• // Abstract method
• void sayMore(String msg);
• // static method
• static void sayLouder(String msg){
• System.out.println(msg);
• }
• }

07/02/2024 9
• public class DefaultMethods implements Sayable{
• public void sayMore(String msg){
• //implementing abstract method
• System.out.println(msg); }
• public static void main(String[] args) {
• DefaultMethods dm = new DefaultMethods();
• dm.say(); // calling default method

• dm.sayMore("Work is worship"); // calling abstract method

• Sayable.sayLouder("Hello, this is static method");


• // calling static method
• } }
• Output:
• Hello, this is default method
07/02/2024 10
• Work is worship
Java Functional Interfaces
• An Interface that contains exactly one abstract
method is known as functional interface. It can
have any number of default, static methods but can
contain only one abstract method. It can also declare
methods of object class.

• Functional Interface is also known as Single Abstract


Method Interfaces or SAM Interfaces. It is a new
feature in Java, which helps to achieve functional
programming approach.
07/02/2024 11
• @FunctionalInterface
• interface sayable{
• void say(String msg);
• }
• public class FunctionalInterfaceExample implements sayable{
• public void say(String msg){
• System.out.println(msg);
• }
• public static void main(String[] args) {
• FunctionalInterfaceExample fie = new
FunctionalInterfaceExample();
• fie.say("Hello there");
• }
• }
• output:
• 07/02/2024 12
Hello there
• A functional interface can have methods of object class.
• @FunctionalInterface
• interface sayable{
• void say(String msg); // abstract method
• // It can contain any number of Object class methods.
• int hashCode();
• String toString();
• boolean equals(Object obj);
• }
• public class FunctionalInterfaceExample2 implements sayable{
• public void say(String msg){
• System.out.println(msg);
• }
• public static void main(String[] args) {
• FunctionalInterfaceExample2 fie = new FunctionalInterfaceExample2();
• fie.say("Hello there");
• }
• }
• output:
• Hello there
07/02/2024 13
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.
• 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.
• Why use Lambda Expression?
• To provide the implementation of Functional interface.
• Less coding.
07/02/2024 14
Java Lambda Expressions
• 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:
• () -> {
• //Body of no parameter lambda
• }
07/02/2024 15
Java Lambda Expressions
• One Parameter Syntax:
• (p1) -> {
• //Body of single parameter lambda
• }
• Two Parameter Syntax:
• (p1,p2) -> {
• //Body of multiple parameter lambda
• }

07/02/2024 16
Java Lambda Expressions
• Without Lambda Expression:
• interface Drawable{
• public void draw();
• }
• public class LambdaExpressionExample {
• public static void main(String[] args) {
• int width=10;
• //without lambda, Drawable implementation using anonymous class
• Drawable d=new Drawable(){
• public void draw(){System.out.println("Drawing "+width);}
• }
• d.draw();
• }
• }
• Output: Drawing 10
07/02/2024 17
Java Lambda Expressions
• Java Lambda Expression Example:
• @FunctionalInterface //It is optional
• interface Drawable{
• public void draw();
• }
• public class LambdaExpressionExample2 {
• public static void main(String[] args) {
• int width=10;

• //with lambda
• Drawable d2=()->{
• System.out.println("Drawing "+width);
• };
• d2.draw();
• }
• }
07/02/2024 Output: Drawing 10 18
Java Lambda Expressions
• Java Lambda Expression Example: Single Parameter:
• interface Sayable{
• public String say(String name);
• }
• public class LambdaExpressionExample4{
• public static void main(String[] args) {

• // Lambda expression with single parameter.
• Sayable s1=(name)->{
• return "Hello, "+name;
• };
• System.out.println(s1.say("Sonoo"));

• // You can omit function parentheses
• Sayable s2= name ->{
• return "Hello, "+name;
• };
• System.out.println(s2.say("Sonoo"));
• } Output: Hello, Sonoo
• } Hello, Sonoo
07/02/2024 19
Java Lambda Expressions
• Java Lambda Expression Example: Multiple Parameter:
• interface Addable{
• int add(int a,int b);
• }

• public class LambdaExpressionExample5{
• public static void main(String[] args) {

• // Multiple parameters in lambda expression
• Addable ad1=(a,b)->(a+b);
• System.out.println(ad1.add(10,20));

• // Multiple parameters with data type in lambda expression
• Addable ad2=(int a,int b)->(a+b);
• System.out.println(ad2.add(100,200));
• }
• }
• Output:
• 30
• 300
07/02/2024 20
Streams
• Java provides a new additional package in Java 8 called java.util.stream.
This package consists of classes, interfaces and enum to allows functional-
style operations on the elements. You can use stream by importing
java.util.stream package.

• Stream provides following features:


• Stream does not store elements. It simply conveys elements from a source
such as a data structure, an array, or an I/O channel, through a pipeline of
computational operations.
• Stream is functional in nature. Operations performed on a stream does not
modify it's source. For example, filtering a Stream obtained from a collection
produces a new Stream without the filtered elements, rather than removing
elements from the source collection.
• Stream is lazy and evaluates code only when required.
• The elements of a stream are only visited once during the life of a stream.
Like an Iterator, a new stream must be generated to revisit the same
elements of the source.
07/02/2024 21
Streams
• there are various Java Stream Interface Methods.
• Java Example: Filtering Collection without using Stream
• import java.util.*;
• class Product{
• int id;
• String name;
• float price;
• public Product(int id, String name, float price) {
• this.id = id;
• this.name = name;
• this.price = price;
• }
• }

07/02/2024 22
Streams
• public class JavaStreamExample {
• public static void main(String[] args) {
• List<Product> productsList = new ArrayList<Product>();
• //Adding Products
• productsList.add(new Product(1,"HP Laptop",25000f));
• productsList.add(new Product(2,"Dell Laptop",30000f));
• productsList.add(new Product(3,"Lenevo Laptop",28000f));
• productsList.add(new Product(4,"Sony Laptop",28000f));
• productsList.add(new Product(5,"Apple Laptop",90000f));
• List<Float> productPriceList = new ArrayList<Float>();
• for(Product product: productsList){
• // filtering data of list
• if(product.price<30000){
• productPriceList.add(product.price); // adding price to a
productPriceList
• } }
• System.out.println(productPriceList); // displaying data
07/02/2024 23
• } }
Streams
• Java Stream Example: Filtering Collection by using Stream
• import java.util.*;
• import java.util.stream.Collectors;
• class Product{
• int id;
• String name;
• float price;
• public Product(int id, String name, float price) {
• this.id = id;
• this.name = name;
• this.price = price;
• }
• }

07/02/2024 24
Streams
• Java Stream Example: Filtering Collection by using Stream
• public class JavaStreamExample {
• public static void main(String[] args) {
• List<Product> productsList = new ArrayList<Product>();
• //Adding Products
• productsList.add(new Product(1,"HP Laptop",25000f));
• productsList.add(new Product(2,"Dell Laptop",30000f));
• productsList.add(new Product(3,"Lenevo Laptop",28000f));
• productsList.add(new Product(4,"Sony Laptop",28000f));
• productsList.add(new Product(5,"Apple Laptop",90000f));
• List<Float> productPriceList2 =productsList.stream()
• .filter(p -> p.price > 30000)// filtering data
• .map(p->p.price) // fetching price
• .collect(Collectors.toList()); // collecting as list
• System.out.println(productPriceList2);
• 07/02/2024
} 25
• }
Streams
• Java Stream Iterating Example
• You can use stream to iterate any number of times. Stream provides
predefined methods to deal with the logic you implement. In the following
example, we are iterating, filtering and passed a limit to fix the iteration.

• import java.util.stream.*;
• public class JavaStreamExample {
• public static void main(String[] args){
• Stream.iterate(1, element->element+1)
• .filter(element->element%5==0)
• .limit(5)
• .forEach(System.out::println);
• }
• } Output:5
• 10 15 20 25
07/02/2024 26
MCQs
• In Java 8 Interfaces, methods can be:

• a.default
• b.abstract
• c.all
• d.none

c
07/02/2024 27
• Which is correct encoder method of
Base64 URL encoder?

a) base64.decoder
b) getUrlencoder
c) getUrldecoder
d) base64.getUrlencoder

07/02/2024
b 28
• The newly introduced Streams API is
available in which package of java 8:

• a.java.io.streams
• b.java.io.stream
• c.java.util.streams
• d.java.util.stream

07/02/2024 d 29
• how many methods are there in functional
interface in Java 8?

• a.0
• b.1
• c.2
• d.3

07/02/2024 b 30
• Stream operations in java 8 can be divided
into

• a.Terminal types
• b.Intermediate types
• c.All
• d.None

07/02/2024 c 31
• In java 8 Function is ?

• a.Class
• b.Interface
• c.Lambda Expression
• d.Object

07/02/2024 b 32
Thank you!

07/02/2024 33

You might also like