Oopsunit 3
Oopsunit 3
Lecture-13 ●
●
Functional Interfaces
Lambda Expressions
● Default Methods
Topics to Cover
● Static Method
Multi Atoms Plus
Community and Support: Staying updated ensures access to community support and
resources.
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.
Normal Function
Lambda Expression
Key Characteristics:
● 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(); }}
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:
Syntax:
void abstractMethod();
}
Multi Atoms Plus
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 {
}}
Lets Code→
Multi Atoms Plus
Lecture-14 ●
●
Switch Expressions
Yield Keyword
● Text Blocks
Topics to Cover
● Local Variable Type Inference
OOPS WITH JAVA
Unit-3
Multi Atoms Plus
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.
Lets Code ⇒
Multi Atoms Plus
Definition: A text block is a multiline string literal that enhances the readability and
ease of writing strings that span multiple lines.
Java 13 and Beyond : Introduction of text blocks to simplify multiline string handling
Multi Atoms Plus
● 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.
Side-by-Side Comparison
Lets Code ⇒
Multi Atoms Plus
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:
Readability: Makes code easier to read by focusing on variable names and values.
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
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
Example:
Multi Atoms Plus
HashCode:
ToString:
Multi Atoms Plus
Key Benefits
Lets Code →
Multi Atoms Plus
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
Definition: Sealed classes restrict which other classes or interfaces can extend or
implement them.
Multi Atoms Plus
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
Diamond Syntax
Diamond syntax, introduced in Java 7, simplifies the instantiation of generic classes by
allowing the compiler to infer the type arguments.
Definition: Diamond syntax (<>) allows the compiler to infer the type arguments of a
generic class, reducing boilerplate code.
Syntax:
Before Diamond:
Multi Atoms Plus
Key Benefits
Reduced Boilerplate: Less repetitive code, especially when dealing with complex
generic types.
Lets Code →
Multi Atoms Plus
Syntax:
collection.forEach(action);
action: The action to be performed for each element (typically a lambda expression).
Multi Atoms Plus
Example:
This code prints each element in the list using a lambda expression.
Key Benefits
Lets Code →
Multi Atoms Plus
Lecture-16
Introduction to Java New Features -
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.
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 { try(resource){
Use Use
} }
catch(exception e){ catch(exception e){
Handle Handle
} }
Finally{
Close 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.
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.
Example:
Multi Atoms Plus
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
Why Stream?
Conciseness: Reduces boilerplate code.
Readability: Improves code clarity.
Performance: Optimizes data processing with lazy evaluation.
Multi Atoms Plus
Traditional Way
Stream Operations
Stream operations in Java are divided into two main categories: intermediate
operations and terminal operations.
● Filter ● ForEach
● Map ● Collect
● Sorted ● Reduce
Multi Atoms Plus
Intermediate Operations
1. Filter Operation
2. Map Operation
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
module moduleName {
requires otherModule;
exports com.example.package;
}
Multi Atoms Plus
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
--module-path mods: Specifies the module path where the compiled modules are
located (mods directory).
Thank You