0% found this document useful (0 votes)
18 views18 pages

Unit-3 Oopj

Uploaded by

Pari Aggarwal
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)
18 views18 pages

Unit-3 Oopj

Uploaded by

Pari Aggarwal
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/ 18

UNIT- 3 rd

Functional Interfaces in Java

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.

Java Predefined-Functional Interfaces

Java provides predefined functional interfaces to deal with functional


programming by using lambda and method references.

You can also define your own custom functional interface. Following is
the list of functional interface which are placed in java.util.function
package.

1. Consumer
The consumer interface of the functional interface is the one that
accepts only one argument or a gentrified argument. The consumer
interface has no return value. It returns nothing. There are also
functional variants of the Consumer — DoubleConsumer,
IntConsumer, and LongConsumer. These variants accept primitive
values as arguments.

2-Function
A function is a type of functional interface in Java that receives only a
single argument and returns a value after the required processing.
There are many versions of Function interfaces because a primitive
type can’t imply a general type argument, so we need these versions of
function interfaces. Many different versions of the function interfaces
are instrumental and are commonly used in primitive types like double,
int, long. The different sequences of these primitive types are also used
in the argument.

3-Supplier
The Supplier functional interface is also a type of functional interface
that does not take any input or argument and yet returns a single
output. This type of functional interface is generally used in the lazy
generation of values. Supplier functional interfaces are also used for
defining the logic for the generation of any sequence. For example –
The logic behind the Fibonacci Series can be generated with the help
of the Stream. generate method, which is implemented by the Supplier
functional Interface.
The different extensions of the Supplier functional interface hold many
other suppliers functions like BooleanSupplier, DoubleSupplier,
LongSupplier, and IntSupplier. The return type of all these further
specializations is their corresponding primitives only.

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.
Why use Lambda Expression
1. To provide the implementation of Functional interface.
2. Less coding.

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.

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

2) Reference to an Instance Method

like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
3) Reference to a Constructor

You can refer a constructor by using the new keyword. Here, we are
referring constructor with the help of functional interface.

Stream API
Introduced in Java 8, Stream API is used to process collections of
objects. A stream in Java is a sequence of objects that supports various
methods which can be pipelined to produce the desired result.

How to Create Java Stream?


Java Stream Creation is one of the most basic steps before considering
the functionalities of the Java Stream. Below is the syntax given on
how to declare Java Stream.

Stream<T> stream;

Java Stream Features

The features of Java stream are mentioned below:


 A stream is not a data structure instead it takes input from the
Collections, Arrays or I/O channels.
 Streams don’t change the original data structure, they only provide
the result as per the pipelined methods.
 Each intermediate operation is lazily executed and returns a stream
as a result, hence various intermediate operations can be pipelined.
Terminal operations mark the end of the stream and return the
result.
Different Operations On Streams

There are two types of Operations in Streams:


1. Intermediate Operations
2. Terminate Operations

Intermediate Operations

Characteristics of Intermediate Operations


1. Methods are chained together.
2. Intermediate operations transform a stream into another stream.
3. It enables the concept of filtering where one method filters data and
passes it to another method after processing.

Benefit of Java Stream


There are some benefits because of which we use Stream in Java as
mentioned below:
 No Storage
 Pipeline of Functions
 Laziness
 Can be infinite
 Can be parallelized
 Can be created from collections, arrays, Files Lines, Methods in
Stream, IntStream etc.

Terminal Operations
Terminal Operations are the type of Operations that return the result.
These Operations are not processed further just return a final result
value.

Important Points/Observations of Java Stream


1. A stream consists of a source followed by zero or more intermediate
methods combined together (pipelined) and a terminal method to
process the objects obtained from the source as per the methods
described.
2. Stream is used to compute elements as per the pipelined methods
without altering the original value of the object.

Difference between default and static interface method in Java

Sr. No. Key Static Interface Method Default Method

1 Basic It is a static method which It is a method with


belongs to the interface default keyword and
only. We can write class can override
implementation of this this method
method in interface itself
Sr. No. Key Static Interface Method Default Method

2 Method Static method can invoke It can be invoked on


Invocation only on interface class not interface as well as
on class. class

3 Method Interface and We can override the


Name implementing class , both default method in
can have static method implementing class
with the same name
without overriding each
other.

4. Use Case It can be used as a utility It can be used to


method provide common
functionality in all
implementing
classes

Try-with-resources statement

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.

You can pass any object that implements java.lang.AutoCloseable,


which includes all objects which implement java.io.Closeable.

The following example writes a string into a file. It uses an instance of


FileOutputStream to write data into the file. FileOutputStream is a
resource that must be closed after the program is finished with it. So, in
this example, closing of resource is done by itself try.
Try-with-resources Example

import java.io.FileOutputStream;
public class TryWithResources {
public static void main(String args[]){
// Using try-with-resources
try(FileOutputStream fileOutputStream =newFileOutputStream("/java7-new-
features/src/abc.txt")){
String msg = "Welcome to javaTpoint!";
byte byteArray[] = msg.getBytes(); //converting string into byte array
fileOutputStream.write(byteArray);
System.out.println("Message written to file successfuly!");
}catch(Exception exception){
System.out.println(exception);
}
}
}

Type Annotations, Repeating Annotations

Java 8 has included two new features repeating and type annotations in
its prior annotations topic. In early Java versions, you can apply
annotations only to declarations. After releasing of Java SE 8 ,
annotations can be applied to any type use. It means that annotations can
be used anywhere you use a type. For example, if you want to avoid
NullPointerException in your code, you can declare a string variable like
this:
Java Repeating Annotations
In Java 8 release, Java allows you to repeating annotations in your
source code. It is helpful when you want to reuse annotation for the
same class. You can repeat an annotation anywhere that you would use a
standard annotation.

For compatibility reasons, repeating annotations are stored in a container


annotation that is automatically generated by the Java compiler. In order
for the compiler to do this, two declarations are required in your code.

1. Declare a repeatable annotation type


2. Declare the containing annotation type

1) Declare a repeatable annotation type

Declaring of repeatable annotation type must be marked with the


@Repeatable meta-annotation. In the following example, we have
defined a custom @Game repeatable annotation type.

@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}

2) Declare the containing annotation type

Containing annotation type must have a value element with an array


type. The component type of the array type must be the repeatable
annotation type. In the following example, we are declaring Games
containing annotation type:

@interfaceGames{
Game[] value();

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, rt.jar 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.

Apart from JDK, Java also allows us to create our own modules so that
we can develop module based application.

o Includes various options to the Java tools javac, jlink and


java where we can specify module paths that locates to the
location of module.
o Modular JAR file is introduced. This JAR contains module-
info.class file in its root folder.
o JMOD format is introduced, which is a packaging format similar to
JAR except it can include native code and configuration files.
o The JDK and JRE both are reconstructed to accommodate
modules. It improves performance, security and maintainability.
o Java defines a new URI scheme for naming modules, classes and
resources.

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

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

Anonymous Inner Class in Java

Java prerequisite required before adhering forward to grasp about


anonymous Inner class. It is an inner class without a name and for
which only a single object is created. An anonymous inner class can be
useful when making an instance of an object with certain “extras” such
as overriding methods of a class or interface, without having to
actually subclass a class.

The syntax of an anonymous class expression is like the invocation of


a constructor, except that there is a class definition contained in a
block of code.
Syntax:

// Test can be interface,abstract/concrete class


Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}

};

 A normal class can implement any number of interfaces but the


anonymous inner class can implement only one interface at a time.

 A regular class can extend a class and implement any number of


interfaces simultaneously. But anonymous Inner class can extend a
class or can implement an interface but not both at a time.

 For regular/normal class, we can write any number of constructors


but we can’t write any constructor for anonymous Inner class
because the anonymous class does not have any name and while
defining constructor class name and constructor name must be
same.
Java Variables
Variable

A variable is the name of a reserved area allocated in memory. In other


words, it is a name of the memory location. It is a combination of "vary
+ able" which means its value can be changed.
1) Local Variable

A variable declared inside the body of the method is called local


variable. You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method,
is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and


is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be


local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.

Switch Expressions
The Java switch statement executes one statement from multiple conditions. It
is like if-else-if ladder statement. The switch statement works with byte, short,
int, long, enum types, String and some wrapper types like Byte, Short, Int, and
Long. Since Java 7, you can use strings in the switch statement.

o There can be one or N number of case values for a switch expression.


o The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allows.
o The case values must be unique. In case of duplicate value, it renders
compile-time error.
o The Java switch expression must be of byte, short, int, long (with its
Wrapper type) and string.
o Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the
switch expression. If a break statement is not found, it executes the next
case.
o The case value can have a default label which is optional.
Sealed Class in Java
In programming, security and control flow are the two major concerns that
must be considered while developing an application. There are various
controlling features such as the use of final and protected keyword restricts
the user to access variables and methods. Java 15 introduces a new preview
feature that allows us to control the inheritance. In this section, we will discuss
the preview feature, the concept of sealed class, and interface with proper
examples.

Preview Feature

A feature whose design, implementation, and specification are complete


but not permanent. In future Java SE releases, the feature may exist in
different forms or not at all.

Also, note that the code that has preview feature cannot be compile and
run easily. It requires additional command-line options.

Using Preview Features

If we are using the preview feature in a Java program, we must explicitly


enable the preview feature in the compiler and runtime systems. If we do
not enable the preview feature, we get an error message "preview
feature is disabled by default.
Uses of Sealed Class

o Java Reflection API


o Java Records
o Pattern Matching

Advantages of Sealed Class and Interface


o It allows permission to the subclasses that can extend the sealed
superclass.
o It makes superclass broadly accessible but not broadly extensible.
o It allows compilers to enforce the type system on the users of the
class.
o Developer of a superclass gets control over the subclasses. Hence,
they can define methods in a more restricted way.

You might also like