[go: up one dir, main page]

0% found this document useful (0 votes)
27 views48 pages

Java UnitIII Ppt

Uploaded by

ayuu19628
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)
27 views48 pages

Java UnitIII Ppt

Uploaded by

ayuu19628
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
You are on page 1/ 48

UNIT-III (BCS-403)

IT1- 4th Sem (2nd year),


Monalisa Panigrahi
1. Herbert Schildt, "Java The complete reference", McGraw Hill
Education
2. Steven Holzner, “Java Black Book”, Dreamtech.
3. Balagurusamy E, “Programming in Java”, McGraw Hill
4. Java: A Beginner’s Guide by Herbert Schildt, Oracle Press
Topics (Syllabus)
 Java New Features

 Functional Interfaces,

 Lambda Expression,

 Method References,

 Stream API,

 Default Methods,

 Static Method,

 Base64 Encode and Decode,

 ForEach Method,

 Try-with-resources,

 Type Annotations, Repeating Annotations,

 Java Module System,

 Diamond Syntax with Inner Anonymous Class,

 Local Variable Type Inference, Switch Expressions, Yield Keyword, Text Blocks,
Records, Sealed Classes
Lambda Expression
 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.
 The Lambda expression is used to provide the implementation
of an interface which has functional interface.
 It saves a lot of code.
Why use Lambda Expression

 To provide the implementation of Functional interface.


 Less coding.
Java Lambda Expression
Syntax
 (argument-list) -> {body}

 Java lambda expression consists 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. }
Lambda Expression Example:
No Parameter Syntax

 public static void main()


 {
 System.out.print(“Hello”);
 }

 Lambda Expression :
 () -> { System.out.print(“Hello”); }
 () -> System.out.print(“Hello”);
Lambda Expression Example:
One Parameter Syntax
 public int m1(String s)
 {
 return s.length ();
 }

 Lambda Expression :
 (String s) -> { return s.length(); }
 (String s) -> return s.length();
 s -> s.length();
Lambda Expression Example:
Two Parameter Syntax
 public void sum (int a, int b)
 {
 System.out.print (a+b);
 }

 Lambda Expression :
 (int a, int b) -> { System.out.print(a+b); }
 (int a, int b) -> System.out.print(a+b);
 (a,b) -> System.out.print(a+b);
Functional Interfaces
 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.

 A functional interface can have any number of default methods.

 Functional interfaces are included in Java SE 8 with Lambda


expressions and Method references in order to make code more
readable, clean, and straightforward.
Functional Interfaces

 Functional Interface is additionally recognized as Single


Abstract Method Interfaces.

 In short, they are also known as SAM interfaces.

 Functional interfaces in Java are the new feature that


provides users with the approach of fundamental
programming.
Without Lambda Expression
using only interface
1. interface Drawable{

2. public void draw();

3. }

4. public class LambdaExpressionExample {

5. public static void main(String[] args) {

6. int width=10;

7. //without lambda, Drawable implementation using anonymous class

8. Drawable d=new Drawable(){

9. public void draw(){System.out.println("Drawing "+width);}

10. };

11. d.draw();

12. }

13. }
With Lambda Expression and
Functional Interface
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. }
Java Method References

 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.
Types of Method References

 Reference to a static method.


 Reference to an instance method.
 Reference to a constructor.
Reference to a static method
 ContainingClass::staticMethodName
@FunctionalInterface
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is
static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable =
MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
Reference to an Instance
Method  containingObject::instanceMethodName
@FunctionalInterface

interface Sayable{

void say();

public class MethodRef1 {

public void saySomething(){

System.out.println("Hello, this is non-static method.");

public static void main(String[] args) {

MethodRef1 methodReference = new MethodRef1(); // Creating object

// Referring non-static method using reference

Sayable sayable = methodReference::saySomething;

// Calling interface method

sayable.say();

// Referring non-static method using anonymous object

Sayable sayable2 = new MethodRef1()::saySomething; // You can use anonymous object also

// Calling interface method

sayable2.say();
Reference to a Constructor

interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
 ClassName::new
Stream API

 Java provides a new additional package in Java 8 called


java.util.stream.
 This package consists of classes, interfaces to allows
functional-style operations on the elements.
 You can use stream by importing java.util.stream
package.
 You can use stream to filter, collect, print, and convert from
one data structure to other etc.
Default Method
 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.


Static Methods

 Static methods are used to define


utility methods and can be
accessed in the program by only
using the class name.
Base64 Encode and Decode

 Java provides a class Base64 to deal with encryption.


 You can encrypt and decrypt your data by using
provided methods.
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.
ForEach Method

 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.
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.
 Module is a collection of Java programs or softwares. To
describe a module, a Java file module-info.java is
required. This file also known as module descriptor and
defines the following
 Module name
 What does it export
 What does it require
How to create Java module

 Creating Java module required the following steps.

 Create a directory structure


 Create a module declarator
 Java source code
Diamond Syntax with Inner
Anonymous Class
 Diamond Syntax

 Inner Anonymous Class


Diamond Operator : < >
 Diamond operator was introduced in Java 7 as
a new feature.

 List<String> Address = new ArrayList<>();

 This line declares and initializes a variable for


storing a list of strings.
Anonymous Inner Class

 It is an inner class without a name and for which only a


single object is created.
// Java program to demonstrate Need for
// Anonymous Inner class
// Interface
interface Age {
// Defining variables and methods
int x = 21;
void getAge();
}
// Class 1
// Helper class implementing methods of Age Interface
class MyClass implements Age {
// Overriding getAge() method
@Override public void getAge()
{
// Print statement
System.out.print("Age is " + x);
}
}
// Class 2
// Main class
// AnonymousDemo
class Example {
// Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();
obj.getAge();
}
}
Local Variable Type Inference

 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.
 Old style
 String name = "Welcome to tutorialspoint.com";

 New Style
 var name = "Welcome to tutorialspoint.com";
Switch Expressions
Yield Keyword

 A new keyword yield has been


introduced in Java 13.

 It returns values from a switch


branch only.
Text Blocks

 Introduced in Java 15 to declare


multi-line strings easily.

 Text blocks begin with a “”” (3


double-quote marks) observed
through whitespaces and a newline.
Records
 Records are known as the data structure to store the
fixed number of elements. (Java 14)
Without Records
 public class Person {

 private final String name;

 private final int age;

 public Person(String name, int age) {

 this.name = name;

 this.age = age;

 }

 public String getName() {

 return name;

 }

 public int getAge() {

 return age;

 }

 }
With Records

 public record Person(String name, int age)


{ }
Sealed Classes
 Java 15 introduced the concept of sealed classes.
 It is a preview feature, not a permanent feature.
 Java sealed classes and interfaces restrict that which
classes and interfaces may extend or implement them.
 Define the class that you want to make a seal.
 Add the “sealed” keyword to the class and specify
which classes are permitted to inherit it by using the
“permits” keyword.
Annotations

 Annotation is type of comment which is used to provide meta


data to the compiler and JVM about the program.
 annotation is used to provide meta data to the compiler and JVM
about the program but comment is used to provide information
to the programmer.
 Annotations are used to provide supplemental information about
a program.
 Annotations start with ‘@’.
 Annotations do not change the action of a compiled program.
Type and Repeating Annotations

 Introduced as new features in Java 8.


 Type Annotations means that annotations can be used
anywhere you use a type.
 Ex: if you want to avoid NullPointerException in your code,
you can declare a string variable
 @NonNull String str;
Repeating Annotations

 It is helpful when you want to reuse annotation for the same


class.
Try-with-resources

 In Java, the try-with-resources statement is a try


statement that declares one or more resources.
 The resource is as an object that must be closed after
finishing the program.
 The try-with-resources statement ensures that each
resource is closed at the end of the statement
execution.
Features HashSet LinkedHashSet TreeSet

LinkedHashSet
HashSet
uses TreeSet uses TreeMap
Internal internally uses
LinkedHashMap internally to store
Working HashMap for
internally to store objects
storing objects
objects

If you don’t
If you want to
want to
maintain the If you want to sort the
maintain
When To insertion order of elements according to
insertion order
Use elements then you some Comparator then
but want to
can use use TreeSet
store unique
LinkedHashSet
objects

While TreeSet orders


the elements according
LinkedHashSet to supplied
HashSet does
maintains the Comparator. By
Order not maintain
insertion order of default, objects will be
insertion order
objects placed according to
their natural ascending
order.

LinkedHashSet
HashSet gives While TreeSet gives
gives insertion,
O(1) complexity the performance of
Complexity removing, and
for insertion, order O(log(n)) for
of retrieving
removing, and insertion, removing,
Operations operations
retrieving and retrieving
performance in
objects operations.
order O(1).

The The performance of TreeSet performance is


performance of LinkedHashSet is better than
HashSet is slower than LinkedHashSet except
Performance better when TreeSet. It is for insertion and
compared to almost similar to removal operations
LinkedHashSet HashSet but slower because it has to sort
and TreeSet. because the elements after each
LinkedHashSet insertion and removal

You might also like