0% found this document useful (0 votes)
2 views42 pages

Bitwise Learning Java Unit 3

Uploaded by

akashteja06
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)
2 views42 pages

Bitwise Learning Java Unit 3

Uploaded by

akashteja06
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

W I

I T S

E
OBJECT ORIENTED E

G
A R N
N I

T W I
PROGRAMMING WITH JAVA
I S

E
(BCS-403)

Unit-III: Java New Features


L E

G
Complete
A R N
Notes
I
N
OOPS WITH JAVA (BCS-403)

UNIT 3 - SYLLABUS
T W I
I S

E
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
L E

G
A R N
N I

2
OOPS WITH JAVA (BCS-403)

Functional Interfaces
Theory:
T W I S
I
A Functional Interface is an interface that contains exactly one abstract method (often referred to as

E
SAM - Single Abstract Method). Introduced in Java 8, they act as the foundation for bringing
functional programming concepts into Java. They provide the target data type for Lambda
Expressions.
Key Rules & Characteristics:
It can have only one unimplemented (abstract) method. This single method represents the single
functionality the interface exhibits.
L

G
E
It can contain any number of default orA N
static methods without losing its functional status (because
these methods have bodies).
R N I
The @FunctionalInterface Annotation: This metadata tag is placed above the interface. While
optional, it is highly recommended. It forces the compiler to check the interface strictly. If a
programmer accidentally adds a second abstract method, the compiler will throw a syntax error. 3
OOPS WITH JAVA (BCS-403)

Functional Interfaces
Standard Examples: Runnable (contains onlyW
run()), Comparator (contains only compare())
T I S
I

E
L

G
E
A N
R N I

4
OOPS WITH JAVA (BCS-403)

Lambda Expression
Theory:
T W I S
I to represent an anonymous function—a method that
A Lambda Expression is a highly concise way

E
does not have a name, a return type declaration, or an access modifier (like public/private)
Key Rules & Characteristics:
Reduces Boilerplate: It completely eliminates the need to write bulky, verbose Anonymous Inner
Classes.
Functional Style: It allows functions to be passed around as parameters to other methods or stored
in variables.
L

G
E
Type Inference: The Java compiler is smart N
A enough to automatically
I
infer (guess) the data types of
R N
the parameters passed based on the target functional interface, reducing verbosity.
Code Example:
(parameters) -> { body/expression }. The arrow -> separates the parameters from the implementation.
5
OOPS WITH JAVA (BCS-403)

Lambda Expression

T W I S
I

E
L

G
E
A N
R N I

6
OOPS WITH JAVA (BCS-403)

Method References

Theory: T W I S
I
Method reference is an even shorter, compact shorthand syntax that allows you to refer to an existing

E
method by its name instead of invoking it directly using a lambda expression. If your lambda
expression's body is simply doing nothing but calling an existing method, you can replace it entirely
with a Method Reference.
Key Rules & Characteristics:
It utilizes the double colon :: operator
L

G
Code Example: E
A N
I maintains strict type safety
Vastly improves code readability, promotes codeRreuse,
N and

7
OOPS WITH JAVA (BCS-403)

Method References
Three Types of Method References:
T W I S
I
Reference to a Static Method: ClassName::staticMethodName

E
Reference to an Instance Method of an Object: instanceReference::methodName
Reference to a Constructor: ClassName::new

G
E
A N
R N I

8
OOPS WITH JAVA (BCS-403)

Method References

T W I S
I

E
L

G
E
A N
R N I

9
OOPS WITH JAVA (BCS-403)

Default & Static Methods in Interfaces


Before Java 8, interfaces could only contain abstract methods. This created a massive limitation:
T W I
I
adding a new method to an old interface would break all S
existing classes that implemented it, forcing

E
developers to rewrite massive amounts of code.
A. Default Methods:
Theory: Methods defined inside an interface with a full body, tagged with the default keyword.
Purpose (Backward Compatibility): They enable developers to add new functionality to existing
interfaces seamlessly. Older classes implementing the interface inherit the default method
automatically without breaking. Subclasses can optionally override them if they need custom
L

G
E
behavior.
A I N
R N
Multiple Inheritance Conflict: If a class implements two interfaces that both have a default method
with the exact same name and signature, a conflict occurs. The class must override the method to
resolve the ambiguity.
10
OOPS WITH JAVA (BCS-403)

Default & Static Methods in Interfaces


B. Static Methods:
T W I S
I keyword inside an interface.
Theory: Methods defined using the static

E
Rule: Because they are static, they belong strictly to the interface itself. They cannot be overridden
by implementing subclasses, and they must be called strictly using the interface name (e.g.,
[Link]()).

G
E
A N
R N I

11
OOPS WITH JAVA (BCS-403)

Default & Static Methods in Interfaces

T W I
Feature Default Method
I S Static Method

E
A method in an interface that has a body A method in an interface declared using the
Definition
and uses the default keyword static keyword

Introduced In Java 8 Java 8

To provide a default implementation to To provide utility/helper methods related to the


Purpose
L

G
implementing classes interface
E
A N
R N I
Keyword Used default static

Written inside the interface with method


Implementation Written inside the interface with method body
body
12
OOPS WITH JAVA (BCS-403)

Default & Static Methods in Interfaces

T W I S
I
Feature Default Method Static Method

E
Called using the object of the implementing
Access Called using the interface name
class

Overriding Can be overridden by implementing classes Cannot be overridden by implementing classes

G
E
Inheritance N
Inherited by implementing classes
A Not inherited by implementing classes
R N I
Example Call [Link]() [Link]()

13
OOPS WITH JAVA (BCS-403)

Stream API
Theory:
T W I S
I
Found in the [Link] package, a Stream is a powerful sequence of elements from a collection

E
(like a List or Array) that supports functional-style, sequential, and parallel aggregate operations.
Core Concepts:
Streams do not store data. They compute data on-demand.
They heavily utilize Lambda Expressions to process massive datasets efficiently without writing
traditional, explicit for loops.
Types of Operations:
L

G
E
Intermediate Operations: These transform, I N
A filter, or manipulate a stream and return a new stream.
R N
They are lazy, meaning they don't execute until a terminal operation is called. Examples: filter()
(selects based on condition), map() (transforms data), sorted(), distinct().

14
OOPS WITH JAVA (BCS-403)

Stream API
W orI a side effect and permanently close the stream.
Terminal Operations: These produce a final result
T
I S
Examples: collect() (gathers into a List), reduce() (computes a single value like sum/max),

E
forEach(), count().

G
E
A N
R N I

15
OOPS WITH JAVA (BCS-403)

Stream API

T W I S
I

E
L

G
E
A N
R N I

16
OOPS WITH JAVA (BCS-403)

Stream API

T W I S
I
Calculating Average using mapToInt

E
Finding the Longest String using max
L

G
E
A N
R N I

17
OOPS WITH JAVA (BCS-403)

Base64 Encode and Decode


Theory (The Problem):
T W I S
Computers process binary data (0s and 1s).IWhen sending raw binary data (like images or files) over

E
text-only protocols (like Email or HTTP), the data often contains "NULL bytes". In languages like
C/C++, a NULL byte signifies the end of a string, causing the file transfer to stop prematurely and
resulting in corrupted data.
The Solution:
Base64 Encoding takes raw binary data and converts it into a safe String/Character format. It maps 3
bytes of binary data (24 bits) into 4 highly readable ASCII characters (6 bits each, 26=64 characters).
L

G
E
The bloated size is only about 1.33 times theAoriginal.N
R N I
Padding (=):
If the data length is not a multiple of 3 bytes, the encoder automatically adds one or two padding
characters (=) at the end. You can ignore this using .withoutPadding().
18
OOPS WITH JAVA (BCS-403)

Base64 Encode and Decode

T W I S
I

E
L

G
E
A N
R N I

19
OOPS WITH JAVA (BCS-403)

Base64 Encode and Decode

T W I S
I

E
L

G
E
A N
R N I

20
OOPS WITH JAVA (BCS-403)

ForEach Method

Theory: T W I S
I
Introduced in Java 8, it provides an incredibly powerful, concise way to iterate over elements of a

E
collection (like a List, Set, or Map).
Mechanism:
It is an internal iterator defined inside the Iterable interface. It completely eliminates the need for
traditional for or while loops. It takes a single parameter: a Consumer functional interface (via
Lambda Expression), and performs that specified action on every single element in the collection
L

G
sequentially. E
A N
R N I

21
OOPS WITH JAVA (BCS-403)

ForEach Method

T W I S
I

E
L

G
E
A N
R N I

22
OOPS WITH JAVA (BCS-403)

Try-with-resources
Theory:
T W I S
Introduced in Java 7, this is a revolutionaryIautomatic resource management feature. Previously, when

E
using resources like Database Connections, File Readers, or Network Sockets, programmers had to
write a finally block to manually call the .close() method. Forgetting this caused memory and resource
leaks.
Mechanism:
You declare the resource inside the parentheses () immediately following the try keyword. The JVM
guarantees that every resource declared here will be automatically closed at the end of the block,
L

G
E
regardless of whether an exception occurs orA
not. N
R N I
Rule:
To use this feature, the object must implement the [Link] or [Link]

23
OOPS WITH JAVA (BCS-403)

Try-with-resources

T W I S
I

E
L

G
E
A N
R N I

24
OOPS WITH JAVA (BCS-403)

Type Annotations

Theory: T W I S
I
Annotations (@) are tags that provide metadata (data about data) to the compiler, JVM, or

E
development tools. Prior to Java 8, annotations could only be applied to declarations (like defining a
class or method).
Java 8 Upgrade:
Java 8 expanded this heavily. Annotations can now be applied anywhere a type is used. This includes
object creations (new), type casting, generic parameters, and method parameters.
L

G
Purpose: E
A I N
It allows for much stricter compile-time checkingRandN
precision (e.g., catching NullPointerExceptions
before the code even runs).

25
OOPS WITH JAVA (BCS-403)

Type Annotations

T W I S
I

E
L

G
E
A N
R N I

26
OOPS WITH JAVA (BCS-403)

Repeating Annotations
Theory: T W I S
I
Before Java 8, you could not apply the exact same annotation to a single declaration more than once. If

E
a method needed two schedules, you couldn't write @Schedule twice.
Java 8 Upgrade:
You can now repeat annotations. It greatly simplifies scenarios where you need to apply the same
metadata with different values.
Implementation Rule:
L

G
It requires two steps: E
A N
R N I
1. Creating the base annotation marked with @Repeatable.
2. Creating a Container Annotation (an array) that holds the repeated values.

27
OOPS WITH JAVA (BCS-403)

Repeating Annotations

T W I S
I

E
L

G
E
A N
R N I

28
OOPS WITH JAVA (BCS-403)

Java Module System


Theory:
T W I S
Introduced in Java 9, the Module System (Project IJigsaw) was created to fix the issue of massive, monolithic, and

E
heavy JAR files that plagued enterprise Java development.
What is it?
A Module is a level of aggregation higher than a package. It is a strict collection of related packages and resources.
Module Descriptor ([Link]):
Every module must have this file at its root. It uses specific directives:
requires: Explicitly states which other modules this module depends on.
L

G
E packages accessible to the outside world (Strong
exports: Explicitly makes specific internal
A N
Encapsulation). R N I
Goals:
Reliable configuration, greatly improved performance, scalable platform, and stopping accidental internal
API usage. 29
OOPS WITH JAVA (BCS-403)

Diamond Syntax with Inner Anonymous Class

Theory: T W I S
I
The Diamond Operator <> was introduced in Java 7 to simplify the instantiation of generic classes. It allows

E
the compiler to infer the type argument from the left side of the assignment (e.g., List<String> list = new
ArrayList<>();), reducing redundant boilerplate code.
Java 9 Enhancement
Prior to Java 9, the compiler would throw an error if you tried to use the diamond operator <> while
creating an Anonymous Inner Class. Java 9 fixed this limitation, allowing the compiler to automatically
L

G
E
infer types for anonymous classes just like standard objects.
A N
R N I

30
OOPS WITH JAVA (BCS-403)

Local Variable Type Inference (var)


Theory: T W I S
I
Introduced in Java 10, the var keyword shifts the responsibility of determining a variable's data type from

E
the developer to the JDK compiler. The compiler intelligently infers (guesses) the type based on the value
assigned to it during initialization.
Strict Limitations:
It can only be used for local variables (inside method definitions, for-loops, or if-else blocks).
It cannot be used for class-level instance variables (fields) or method parameters.
L

G
E moment of declaration (e.g., var x; is illegal).
The variable must be initialized at the exact
A N
R N I

31
OOPS WITH JAVA (BCS-403)

Local Variable Type Inference (var)

T W I S
I

E
L

G
E
A N
R N I

32
OOPS WITH JAVA (BCS-403)

Switch Expressions & Yield Keyword

Theory (Switch Expressions): T W I S


I
Finalized in Java 14, this upgrades the traditional, bulky switch statement. Switch expressions use a modern

E
arrow syntax (->), they evaluate to a single value that can be assigned directly to a variable, and crucially,
they eliminate the need for the break keyword because they do not "fall through" automatically.
Theory (Yield Keyword):
yield is a context-specific keyword used strictly inside a switch expression's case block { }. If a specific case
requires multiple lines of code (computations or printing) before returning its final value, you cannot use the
L

G
E exit the block and return the value.
simple arrow return. Instead, you use yield to
A N
R N I

33
OOPS WITH JAVA (BCS-403)

Switch Expressions & Yield Keyword

T W I S
I

E
L

G
E
A N
R N I

34
OOPS WITH JAVA (BCS-403)

Text Blocks

T W I S
Theory:
Finalized in Java 15, a Text Block is a multi-lineI string literal.

E
Syntax:
It is enclosed using triple double-quotes """.
Advantage:
Historically, writing HTML, SQL queries, or JSON inside Java was a nightmare of string concatenations (+)
and explicit newline escape sequences (\n). Text blocks solve this. Everything written inside the triple quotes is
L

G
E
preserved exactly as typed—including whitespace, exact indentation, and line breaks—enhancing readability
A N
tremendously. R N I

35
OOPS WITH JAVA (BCS-403)

Text Blocks

T W I S
I

E
L

G
E
A N
R N I

36
OOPS WITH JAVA (BCS-403)

Records
Theory:
T W I S
Finalized in Java 16, record is a special kind of Iclass specifically designed to act as an immutable data carrier (a

E
class whose sole purpose is to hold data, like database fetching results).
The Problem it Solves
Creating a traditional POJO (Plain Old Java Object) class requires writing massive amounts of boilerplate code:
private fields, parameterized constructors, getters, setters, equals(), hashCode(), and toString()methods.
The Record Solution:
L

G
E
By declaring a record, the Java compiler automatically and invisibly generates all of these standard methods for
A N
you. The fields are automatically final (immutable). R N I

37
OOPS WITH JAVA (BCS-403)

Records

T W I S
I

E
L

G
E
A N
R N I

38
OOPS WITH JAVA (BCS-403)

Records

T W I S
I

E
L

G
E
A N
R N I

39
OOPS WITH JAVA (BCS-403)

Sealed Classes
Theory: T W I S
I
Finalized in Java 17, a Sealed Class provides absolute, strict control over Object-Oriented inheritance

E
hierarchies. It allows a developer to explicitly restrict exactly which other classes or interfaces are permitted to
extend or implement it.
Keywords
Created using sealed and permits.
Constraint Rules:
L

G
E a sealed class MUST explicitly declare itself as one of three
Any subclass that is granted permission to extend
A I N
R N
strict modifiers to define how it continues the inheritance chain:
final: The inheritance chain stops here. It cannot be extended further.
sealed: It continues the seal, and must explicitly permit its own specific subclasses.
non-sealed: It breaks the seal, opening itself up to be extended by any unknown class.
40
OOPS WITH JAVA (BCS-403)

Sealed Classes

T W I S
I

E
L

G
E
A N
R N I

41
T W I S
I

E
L

G
E
A N
R N I

42

You might also like