0% found this document useful (0 votes)
28 views76 pages

Oopsunit 3

The document covers new features in Java, including functional interfaces, lambda expressions, default methods, static methods, switch expressions, the yield keyword, text blocks, local variable type inference, records, sealed classes, diamond syntax, and the forEach method. It emphasizes the importance of keeping up with these features for enhanced productivity, performance, and modern development practices. Additionally, it discusses the benefits of each feature, such as improved readability, reduced boilerplate code, and better resource management.

Uploaded by

raza0iop
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)
28 views76 pages

Oopsunit 3

The document covers new features in Java, including functional interfaces, lambda expressions, default methods, static methods, switch expressions, the yield keyword, text blocks, local variable type inference, records, sealed classes, diamond syntax, and the forEach method. It emphasizes the importance of keeping up with these features for enhanced productivity, performance, and modern development practices. Additionally, it discusses the benefits of each feature, such as improved readability, reduced boilerplate code, and better resource management.

Uploaded by

raza0iop
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/ 76

Multi Atoms Plus

OOPS WITH JAVA


UNIT-3 (Java New Features)
Aktu 2nd Year Subject Code - (BCS 403)
Multi Atoms Plus

Introduction to Java New Features -

Lecture-13 ●

Functional Interfaces
Lambda Expressions
● Default Methods
Topics to Cover
● Static Method
Multi Atoms Plus

Java Evolution Timeline


● Java 1.0 (1996) : Initial release, introduction of applets.
● Java 2 (1998): Introduction of Swing, Collections framework.
● Java 5 (2004): Generics, annotations, enumerations, varargs.
● Java 7 (2011): Diamond operator, try-with-resources, switch on strings.
● Java 8 (2014): Lambda expressions, Stream API, Date and Time API.
● Java 9 (2017): Module System (Project Jigsaw).
● Java 10 (2018): Local-variable type inference.
● Java 11 (2018): New String methods, Local-variable syntax for lambda parameters.
● Java 12-17: Continuous improvements and introduction of new features.
Multi Atoms Plus

Importance of Keeping Up with New Features


Enhanced Productivity : New features can make coding faster and more efficient.

Better Performance: Many new features come with performance improvements.

Modern Practices: Keeping up with new features helps in adopting modern


development practices.

Community and Support: Staying updated ensures access to community support and
resources.

Career Advancement: Knowledge of the latest features is often a requirement for


advanced job roles.
Multi Atoms Plus

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.
● Lambda expressions, ● Collectors class,
● Method references, ● ForEach() method,
● Functional interfaces, ● Nashorn JavaScript Engine,
● Stream API, ● Parallel Array Sorting,
● Default methods, ● Type and Repeating Annotations,
● Base64 Encode Decode, ● IO Enhancements,
● Static methods in interface, ● Concurrency Enhancements,
● Optional class, ● JDBC Enhancements etc.
Multi Atoms Plus
Lambda Expressions
Lambda expressions were introduced in Java 8 and represent a significant
enhancement to the Java programming language. A lambda expression provides a clear
and concise way to represent one method interface using an expression.

Definition: A lambda expression in Java is a short block of code which takes in


parameters and returns a value. Lambda expressions are similar to methods, but they
do not need a name and can be implemented right in the body of a method.

● Not having any name


● Not having any return type
● Not having any modifier

Syntax: (parameters) -> { statements; } or (parameters) -> expression;


Multi Atoms Plus

Normal Function

public void add(int a, int b){ Steps to make Lambda expression


from any Function:
System.out.println(a+b); 1. Delete modifier
} 2. Delete Return Type
3. Delete Name of method
4. Put Arrow

Lambda Expression

(int a, int b) - > { System.out.println(a+b);} (a, b) - > {System.out.println(a+b);


Multi Atoms Plus

Benefits of Lambda Expression


● Conciseness: Lambda expressions help to reduce the amount of boilerplate code.
They eliminate the need for anonymous classes and provide a more compact and
readable syntax.
● Readability: By reducing boilerplate, lambda expressions make the code more
readable and easier to maintain.
● Functional Programming: They enable functional programming in Java, which can
lead to cleaner and more efficient code.
● Parallel Processing: They work seamlessly with Java Stream API, which can
leverage multi-core architectures for parallel processing.
Multi Atoms Plus
Functional Interface in Java
A functional interface in Java is an interface that contains exactly one abstract method.
functional interface can have any number of default or static methods without
affecting its functional interface status. It can invoke lambda expression.

Key Characteristics:

● Single Abstract Method: This method can be implemented using a lambda


expression.
● @FunctionalInterface Annotation : Java provides the @FunctionalInterface
annotation to declare an interface as functional. This annotation is optional but
helps to prevent accidental addition of more abstract methods.
Multi Atoms Plus

● Default and Static Methods: A functional interface can have any number of
default or static methods without affecting its functional interface status.
● Inheritance: If an interface inherits another interface that is functional and does
not declare additional abstract methods, it remains a functional interface.

Example:
@FunctionalInterface
interface MyFunctionalInterface {
void myMethod();
}

Lets Code→
Multi Atoms Plus
Using Functional Interfaces with Lambda Expressions
A functional interface can be implemented using a lambda expression, which provides
a concise way to represent an instance of the interface.
@FunctionalInterface
interface MyFunctionalInterface {
void myMethod(); }
public class FunctionalInterfaceExample {
public static void main(String[] args) {
MyFunctionalInterface instance = () -> System.out.println("Hello, world!");
instance.myMethod(); }}

Output → Hello, world! Lets Code→


Multi Atoms Plus

Default Methods
A default method in Java is a method defined in an interface that has a default
implementation. This allows the interface to provide a method that can be used by
implementing classes without forcing them to override it.

Key Points:

● Defined in Interface: The method is defined within an interface.


● Has a Default Implementation: The method includes a default behavior.
● Optional to Override: Implementing classes can use the provided implementation
or override it if they need a different behavior.
Multi Atoms Plus

Syntax:

public interface MyInterface {

void abstractMethod();

default void defaultMethod() {

System.out.println("This is a default method.");

}
Multi Atoms Plus

Multiple Inheritance and Default Methods


When a class implements multiple
interfaces with default methods,
conflicts can arise if the interfaces
contain methods with the same
signature. In such cases, the
implementing class must resolve the
conflict by overriding the method.

Lets Code→
Multi Atoms Plus
Static Method
● A static method in Java is a method that belongs to the class rather than any instance of the
class.
● This means you can call a static method without creating an object of the class.
● Static methods are defined using the static keyword & static methods cannot be overridden
by subclasses.
public interface MyInterface {

static void staticMethod() {

System.out.println("Static method in interface.");

}}

public class StaticMethodInInterfaceExample {

public static void main(String[] args) {

MyInterface.staticMethod(); // Outputs: Static method in interface. }}


Multi Atoms Plus

Key Characteristics of Static Methods


● Class-Level Method: Static methods belong to the class itself, not to any specific
object instance.
● No this Reference: Since static methods are not associated with instances, they
cannot use the this keyword.
● Can Access Static Data: Static methods can access and modify static variables
directly.
● Cannot Access Instance Data Directly: Static methods cannot access instance
variables or instance methods directly. They must use an object reference to do so.

Lets Code→
Multi Atoms Plus

Introduction to Java New Features -

Lecture-14 ●

Switch Expressions
Yield Keyword
● Text Blocks
Topics to Cover
● Local Variable Type Inference
OOPS WITH JAVA
Unit-3
Multi Atoms Plus

1. Introduction to Switch Expressions


What are Switch Expressions?

Definition: Switch expressions extend the traditional switch statement, allowing it to


be used as an expression that returns a value.

Purpose: Simplifies code and enhances readability.

Before Java 12: Only switch statements existed.

Java 12 and Beyond: Introduction of switch expressions as a preview feature; finalized


in Java 14.
Multi Atoms Plus

Traditional ‘switch’ Statement

Limitations of Traditional switch:

● Wordy : Requires writing `break`


statements for each case.
● Error-Prone: Easy to forget `break`,
which can cause mistakes.
● Not Flexible : Cannot be used
directly in expressions to `return`
values.
Multi Atoms Plus

Switch Expression Syntax

● Arrow Token (->): Used instead of case and


break.
● Expression Form : Returns a value.
● Block Form: Can contain multiple statements.
Multi Atoms Plus

2. Introduction to Yield Keyword


What is the Yield Keyword?

Definition: The yield keyword is used within a


switch expression to return a value from a case
block.

Purpose: Allows multi-statement blocks in


switch expressions to return a value.

General Syntax:
Multi Atoms Plus

The yield keyword in Java is used within a switch expression to return a value from a
case block. This is particularly useful when you need to perform multiple operations or
computations within a case before returning a result. The yield keyword helps to make
the code more readable and organized.

Benefits of Switch Expressions:


Less Boilerplate Code: No need for explicit break statements.

More Readable: Easier to understand and maintain.

Lets Code ⇒
Multi Atoms Plus

Introduction to Text Blocks


What are Text Blocks?

Definition: A text block is a multiline string literal that enhances the readability and
ease of writing strings that span multiple lines.

Purpose: Simplifies writing and maintaining multiline strings.

Before Java 13 : Multiline strings required concatenation or escape sequences.

Java 13 and Beyond : Introduction of text blocks to simplify multiline string handling
Multi Atoms Plus

Syntax of Text Blocks

● Opening and Closing: Use triple quotes (""") to define a text block.
● Newlines : Preserved as-is within the text block.
● Indentation: Leading whitespace is ignored, making it easy to format.

Used with HTML, JSON etc.


Multi Atoms Plus

Side-by-Side Comparison

Traditional Way Text Block

Lets Code ⇒
Multi Atoms Plus

Local Variable Type Inference in Java


What is Local Variable Type Inference?

Definition: Local Variable Type Inference allows the compiler to infer the type of a
local variable based on the assigned value, using the var keyword.

Purpose: Simplifies code by eliminating the need to explicitly declare variable types.

Before Java 10: Explicit type declaration required for all variables.

Java 10 and Beyond: Introduction of the var keyword for local variable declarations.

Syntax:

var variableName = value;


Multi Atoms Plus

var message = "Hello, World!";

var number = 10;

var list = new ArrayList<String>();

Benefits of Local Variable Type Inference

Conciseness: Reduces boilerplate code.

Readability: Makes code easier to read by focusing on variable names and values.

Maintenance: Simplifies code maintenance by reducing redundancy.


Multi Atoms Plus

Limitations of Local Variable Type Inference

Readability: Can reduce readability if overused or used inappropriately.

Explicit Typing: In some cases, explicit typing can make code more understandable.

Type Clarity: Less clear what type a variable is, especially for complex or less familiar
types.

Lets Code ⇒
Multi Atoms Plus

Introduction to Java New Features -

Lecture-15 ●

Records
Sealed Class
● Diamond Syntax with inner
Topics to Cover Anonymous Class
OOPS WITH JAVA ● ForEach Method
Unit-3
Multi Atoms Plus

Introduction to Records
What are Records?
Definition: Records are a special kind of class in Java designed to model immutable
data carriers with a fixed set of fields.
Purpose: Provide a concise syntax to create data classes with automatic
implementations of common methods.
Features of Records
Immutable: Fields are final and cannot be changed once set.
Concise Syntax: Reduces boilerplate code for data classes.
Automatic Methods: Generates constructor, getter, equals(), hashCode(), and
toString() methods.
Multi Atoms Plus
Traditional Classes Vs Records
Traditional Class: Record:
Multi Atoms Plus

Syntax and Examples


Syntax:

Example:
Multi Atoms Plus

Automatic Method Implementations


Equals:

HashCode:

ToString:
Multi Atoms Plus

Key Benefits

Conciseness: Reduces boilerplate code for data classes.

Immutability: Fields are automatically final, making records immutable.

Readability: Makes code cleaner and more readable by reducing verbosity.

Automatic Methods: Provides automatic implementations for equals(), hashCode(),


and toString().

Lets Code →
Multi Atoms Plus

Introduction to Sealed Classes

Sealed classes, introduced in Java 15 as a preview feature and finalized in Java 17,
restrict which other classes or interfaces can extend or implement them. This allows
for more control over the class hierarchy

What are Sealed Classes?

Definition: Sealed classes restrict which other classes or interfaces can extend or
implement them.
Multi Atoms Plus

Features of Sealed Classes

Restricted Hierarchies: Only specific classes can extend a sealed class.

Enhanced Control: Helps in maintaining a well-defined class structure.

Combines with Permits: Uses the permits keyword to specify allowed subclasses.

Syntax:

Explanation: The Shape class can only be extended by Circle and Rectangle.
Multi Atoms Plus
Example: Subclasses can be final, non-sealed or sealed

Final: The subclass cannot be extended further.


Sealed: The subclass can be further restricted with specified permitted subclasses.
Non-Sealed: The subclass can be extended by any other class.
Lets Code →
Multi Atoms Plus

Diamond Syntax
Diamond syntax, introduced in Java 7, simplifies the instantiation of generic classes by
allowing the compiler to infer the type arguments.

What is Diamond Syntax?

Definition: Diamond syntax (<>) allows the compiler to infer the type arguments of a
generic class, reducing boilerplate code.

Purpose: Simplifies code and improves readability by removing redundant type


information.

Syntax:

Before Diamond:
Multi Atoms Plus

Key Benefits

Reduced Boilerplate: Less repetitive code, especially when dealing with complex
generic types.

Improved Readability: Cleaner and more concise code.

Type Safety: Ensures type safety without explicit type declarations.


Multi Atoms Plus
Diamond Syntax with Inner Anonymous Class

Lets Code →
Multi Atoms Plus

Introduction to ForEach Method


● The forEach method, introduced in Java 8, is a powerful way to iterate over
collections using lambda expressions.
● The forEach method is used to perform an action for each element of the
collection.

Syntax:

collection.forEach(action);

collection: The collection to iterate over. (list, map etc)

action: The action to be performed for each element (typically a lambda expression).
Multi Atoms Plus
Example:

List<String> list = Arrays.asList("A", "B", "C");

list.forEach(element -> System.out.println(element));

This code prints each element in the list using a lambda expression.

Key Benefits

Concise Code: Reduces boilerplate code for iteration.

Readability: Enhances readability with clear and concise syntax.

Lets Code →
Multi Atoms Plus

Lecture-16
Introduction to Java New Features -

● Base64 Encode and Decode


● Try-with-resources
● Type Annotations
Topics to Cover
● Repeating Annotations
OOPS WITH JAVA
Unit-3
Multi Atoms Plus

Base64 Encode and Decode in Java


Base64 encoding is a way to convert binary data into a text representation, which can
be easily transmitted or stored. Java provides a Base64 utility class ‘java.util.Base64’ to
encode and decode data.

When to Use Base64 Encoding?

Usage: Commonly used in email (MIME), storing complex data in XML or JSON, and
encoding data in URLs.

● Base64 Encoding: Converts binary data to text format for easy transmission.
● Base64 Decoding: Converts Base64 encoded text back to binary data.
Multi Atoms Plus
Encoding Data in Java

Output:
Multi Atoms Plus
Decoding Data in Java

Output:
Multi Atoms Plus

Introduction to Try-with-Resources
The try-with-resources statement, introduced in Java 7, simplifies resource
management by automatically closing resources when they are no longer needed. It
ensures that each resource is closed at the end of the statement, reducing the likelihood
of resource leaks.

Definition: Try-with-resources is a statement that declares one or more resources,


which are automatically closed at the end of the statement.

Purpose: Simplifies resource management and helps prevent resource leaks.

Usage: Commonly used with resources such as files, database connections, sockets,
and streams that need to be closed after use.
Multi Atoms Plus

Syntax:

try (ResourceType resource = new ResourceType()) {

// Use the resource

ResourceType : The type of the resource being used.

resource: The variable representing the resource.


Multi Atoms Plus
Before try with resource After try with resource

try { try(resource){

Use Use

} }
catch(exception e){ catch(exception e){
Handle Handle
} }
Finally{
Close resource
}
Multi Atoms Plus

Without try with resource With try with resource


Multi Atoms Plus

Annotations in Java
Annotations provide metadata about the program that is not part of the program itself.
They have no direct effect on the code but provide information to the compiler and
tools.

Usage: Commonly used for configuration, documentation, and debugging.

Examples: @Override, @Deprecated, @SuppressWarnings.


Multi Atoms Plus
Introduction to Type Annotations
Type annotations, introduced in Java 8, allow annotations to be used anywhere a type
is used. This provides additional flexibility and precision in adding metadata to the
code.

Definition: Type annotations are annotations that can be applied to any use of a type,
including type declarations, type casts, and type parameters.

Purpose: Provide additional information to the compiler and tools to improve code
quality and enable advanced features.
Multi Atoms Plus
Introduction to Repeating Annotations
Repeating annotations, introduced in Java 8, allow the same annotation to be applied
multiple times to the same declaration or type use. This feature simplifies scenarios
where you need to apply the same annotation with different values.

@Repeatable: Indicates that the annotation can


be repeated.

Schedules: A container annotation that holds an


array of Schedule annotations.

1. Declare a repeatable annotation type


2. Declare the containing annotation type
Multi Atoms Plus

Example:
Multi Atoms Plus

Introduction to Java New Features -

Lecture-17 ● Method References,


● Stream API
Topics to Cover ● Java Module System
OOPS WITH JAVA
Unit-3
Multi Atoms Plus

Method References in Java


Method references are a shorthand syntax for calling a method by referring to it with
the help of its class directly. They make the code more readable and concise, especially
when used with functional interfaces and lambda expressions.

What are Method References?

Definition: Method references provide a way to refer to methods without invoking


them. They can be used to point to a method by name instead of calling it directly.

Benefits: Improves code readability and reduces boilerplate code.


Multi Atoms Plus

Types of Method References

1. Static Method References: ClassName::staticMethodName


2. Instance Method References of a Particular Object:
instance::instanceMethodName
3. Constructor References: ClassName::new

Static Method References:


Multi Atoms Plus

Instance Method References of a Particular Object:


Multi Atoms Plus
Constructor References: ClassName::new
You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.

Key Benefits
● Conciseness: Reduces the
verbosity of lambda expressions.
● Readability: Makes the code
easier to understand.
● Reusability: Enables the reuse of
existing methods.
Multi Atoms Plus

Introduction to Stream API


The Stream API, introduced in Java 8, provides a powerful and efficient way to process
sequences of elements. It allows for functional-style operations on streams of elements, such
as filtering, mapping, and reducing.
Purpose: It is designed to work with large collections of data efficiently.

Why Stream?
Conciseness: Reduces boilerplate code.
Readability: Improves code clarity.
Performance: Optimizes data processing with lazy evaluation.
Multi Atoms Plus

Traditional Way

With Stream Api


Multi Atoms Plus
How to Create Stream
Multi Atoms Plus

Stream Operations
Stream operations in Java are divided into two main categories: intermediate
operations and terminal operations.

Intermediate Operations: Return a stream, enabling method chaining.

Terminal Operations: Produce a result and close the stream.

Intermediate Operations Terminal Operations

● Filter ● ForEach
● Map ● Collect
● Sorted ● Reduce
Multi Atoms Plus
Intermediate Operations
1. Filter Operation

Definition: Selects elements based on a predicate.

2. Map Operation

Definition: Transforms each element using a function.


Multi Atoms Plus
3. Sorted Operation

Definition: Sorts elements based on a comparator.

Terminal Operations
1. ForEach Operation
Definition: Performs an action for each element.
Multi Atoms Plus

Collect Operation
Definition: Accumulates elements into a collection.

Reduce Operation
Definition: Combines elements to produce a single result.
Multi Atoms Plus

List of Stream Operations in Java


Intermediate Operations
filter(Predicate<T> predicate) - Selects elements by condition.

map(Function<T, R> mapper) - Transforms each element.

flatMap(Function<T, Stream<R>> mapper) - Flattens nested streams.

distinct() - Removes duplicate elements.

sorted() - Sorts elements naturally.

sorted(Comparator<T> comparator) - Sorts by comparator.

peek(Consumer<T> action) - Performs action on elements.

limit(long maxSize) - Limits number of elements.

skip(long n) - Skips first n elements.


Multi Atoms Plus
Terminal Operations
forEach(Consumer<T> action) - Performs action for
min(Comparator<T> comparator) - Finds
elements.
minimum element.
forEachOrdered(Consumer<T> action) - Ordered action for
elements. max(Comparator<T> comparator) - Finds
maximum element.
toArray() - Converts stream to array.
count() - Counts elements.
toArray(IntFunction<A[]> generator) - Custom array
conversion.
anyMatch(Predicate<T> predicate) - Checks if
reduce(T identity, BinaryOperator<T> accumulator) - any match.
Combines elements to result.
allMatch(Predicate<T> predicate) - Checks if all
reduce(BinaryOperator<T> accumulator) - Reduces to match.
optional result.

collect(Collector<T, A, R> collector) - Accumulates elements


noneMatch(Predicate<T> predicate) - Checks if
to collection. none match.
collect(Supplier<R> supplier, BiConsumer<R, T> findFirst() - Finds first element.
accumulator, BiConsumer<R, R> combiner) - Custom
collection accumulation. findAny() - Finds any element.
Multi Atoms Plus
Introduction to Java Module System
The Java Module System, introduced in Java 9, is a significant enhancement that allows
developers to organize code into modules, improving modularity and encapsulation.

Modules: A module is a collection of related packages and resources with a descriptor


(module-info.java) that defines the module's dependencies, exported packages, and
other configuration details.

Why Use Modules?

● Modularity: Breaks down complex applications into manageable pieces


● Encapsulation: Controls visibility of code within and across modules
● Dependency Management: Explicitly declares dependencies, avoiding runtime
issues
Multi Atoms Plus
Module: A named unit of code with its own namespace

Module Descriptor: module-info.java file that defines module properties

Requires: Specifies which modules this module depends on

Exports: Makes specific packages accessible to other modules

module moduleName {

requires otherModule;

exports com.example.package;

}
Multi Atoms Plus

Example: Module Descriptors

Module A

Module B
Multi Atoms Plus
Example Directory Structure:
Multi Atoms Plus

Compilation Command:
Open your terminal or command prompt.
Navigate to the root directory of your project (myapp).
javac -d mods --module-source-path src $(find src -name "*.java")
javac: Java compiler command.
-d mods: Specifies the output directory for compiled modules (mods in this case).
--module-source-path src: Indicates the root directory containing module source files (src in
this case).
$(find src -name "*.java"): Finds all .java source files in the src directory and its
subdirectories.
Multi Atoms Plus

Running Command:
java --module-path mods -m moduleA/com.example.moduleA.Main

java: Java runtime command.

--module-path mods: Specifies the module path where the compiled modules are
located (mods directory).

-m moduleA/com.example.moduleA.Main: Indicates the module and the main class


to run. moduleA is the module name, and com.example.moduleA.Main is the fully
qualified name of the main class.
Multi Atoms Plus

● Java Module System enhances the organization and manageability of Java


applications
● Encourages modular design and explicit dependency management
● Essential for modern Java development, especially for large or complex projects
Multi Atoms Plus

Thank You

You might also like