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

Unit-3 Java New Features

The document discusses new features in Java, including abstract methods, default methods, static methods, functional interfaces, lambda expressions, method references, streams, and Base64 encoding/decoding. It explains how these features enhance Java's functionality and provide better programming practices, such as functional programming and improved data handling. Examples are provided for each feature to illustrate their usage and benefits.

Uploaded by

durgeshyadavm15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views33 pages

Unit-3 Java New Features

The document discusses new features in Java, including abstract methods, default methods, static methods, functional interfaces, lambda expressions, method references, streams, and Base64 encoding/decoding. It explains how these features enhance Java's functionality and provide better programming practices, such as functional programming and improved data handling. Examples are provided for each feature to illustrate their usage and benefits.

Uploaded by

durgeshyadavm15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit-3

Java New Features:

PROF. SHIV VEER SINGH (DEPARTM


BY

ENT OF CSE-IOT)
Prof. SHIV VEER SINGH
Abstract Methods
• Abstract methods are methods declared in an abstract class or
in an interface without an implementation. These methods
must be implemented by subclasses or implementing classes.
An abstract method provides a way to enforce certain
behaviors in the subclasses or implementing classes.

PROF. SHIV VEER SINGH (DEPARTM


• Note:
• An abstract method does not have a body (implementation).
• Abstract methods must be declared in abstract classes or

ENT OF CSE-IOT)
interfaces.
• Subclasses of an abstract class must provide implementations
for all abstract methods unless the subclass is also abstract.
• Interfaces in Java can have abstract methods by default (before
Java 8).
• package Unit3;
• abstract class A {
• abstract void am(); // Abstract method (no body)
• void rm() { // Regular method
• System.out.println("Regular method");
• }
• }
• abstract class D extends A { // Providing implementation of abstract method
• void am() {
• System.out.println("Abstract method Implementation of class A");

PROF. SHIV VEER SINGH (DEPARTM


• }
• abstract void am2();
• }
• class E extends D{
• @Override

ENT OF CSE-IOT)
• void am2() {
• System.out.println("Abstract method Implementation of class D");
• }
• }
• public class MainClass {
• public static void main(String[] args) {
• E e = new E();
• e.am();
• e.rm();
• e.am2();
• }
Default Methods
• Default methods were introduced in Java 8 with in interfaces.
These methods have a default implementation and can be
overridden by implementing classes. Default methods allow
developers to add new methods to interfaces without
breaking the existing implementations of those interfaces.

PROF. SHIV VEER SINGH (DEPARTM


• Note:
• Default methods have a body (implementation).
• They can be overridden by implementing classes.

ENT OF CSE-IOT)
• They help in providing backward compatibility.
• package Unit3;
• interface I {
• void am(); // Abstract method
• default void dm() { // Default method
• System.out.println("Default method Calling");
• }
• }
• class DM implements I {
• public void am() { // Providing implementation of abstract method

PROF. SHIV VEER SINGH (DEPARTM


• System.out.println("implementation of abstract method");
• }
• public void dm() { // Overriding default method
• System.out.println("Overriding default method calling");

ENT OF CSE-IOT)
• }
• }
• public class DefaultMethodMainClass {
• public static void main(String[] args) {
• DM d = new DM();
• d.am();
• d.dm();
• }
Static Methods
• Static methods are methods that belong to the class rather
than any instance of the class. They can be called without
creating an instance of the class. Static methods are often used
for utility or helper methods.
• Note:

PROF. SHIV VEER SINGH (DEPARTM


• Static methods belong to the class, not instances of the class.
• They can be called without creating an object of the class.
• Static methods can access static variables and other static

ENT OF CSE-IOT)
methods directly.
• They cannot access instance variables or instance methods
directly.
• class A{
• static int add(int a, int b) { // Static method
• return a + b;
• }
• }
• public class Main {

PROF. SHIV VEER SINGH (DEPARTM


• public static void main(String[] args) {
• // Calling static method without creating an instance of the class
• int sum = A.add(5, 3);

ENT OF CSE-IOT)
• System.out.println("Sum: " + sum); }
• }
Functional Interfaces
• A functional interface is an interface that has exactly one abstract
method. These interfaces are used as the basis for lambda expressions
and method references in Java.
• Functional Interface is also known as Single Abstract Method
Interfaces or SAM Interfaces. It is a new feature in Java, which helps

PROF. SHIV VEER SINGH (DEPARTM


to achieve functional programming approach.
• Note:
1. A functional interface can also have methods of object class.

ENT OF CSE-IOT)
2. A functional interface can extends another interface only when it
does not have any abstract method.
3. It Must have exactly one abstract method.
4. It Can have multiple default or static methods.
5. The @FunctionalInterface annotation can be used to mark an
interface as a functional interface.
• Ex.1
• @FunctionalInterface
• interface MYFunctionalInterface{
• void am(String s);
• }
• public class FunctionalInterfaceExample implements MYFunctionalInterface{
• public void am(String s){

PROF. SHIV VEER SINGH (DEPARTM


• System.out.println(s);
• }
• public static void main(String[] args) {
• FunctionalInterfaceExample fie = new

ENT OF CSE-IOT)
FunctionalInterfaceExample();
• fie.am("MY Functional Interface Example");
• }
• }
Ex.2
• @FunctionalInterface
• interface MYFunctionalInterface{
• void am(String s);
• int hashCode();
• String toString();
• boolean equals(Object obj);

PROF. SHIV VEER SINGH (DEPARTM


• }
• public class FunctionalInterfaceExample implements MYFunctionalInterface{

ENT OF CSE-IOT)
• public void am(String s){
• System.out.println(msg);
• }
• public static void main(String[] args) {
• FunctionalInterfaceExample fie = new FunctionalInterfaceExample();
• fie.am("MY Functional Interface Example");
• }
• }
Lambda Expressions
• A lambda expression is a concise way to represent an anonymous
function (i.e., a function without a name) that can be passed
around. It provides a clear and concise way to implement a method
of a functional interface.
• Note:

PROF. SHIV VEER SINGH (DEPARTM


• Syntax: (parameters) -> expression or (parameters) -> { statements }
• They are used primarily to define the inline implementation of a
functional interface.
• Lambda expressions can be stored in variables if the variable's type

ENT OF CSE-IOT)
is an interface which has only one method. The lambda expression
should have the same number of parameters and the same return
type as that method. Java has many of these kinds of interfaces
built in, such as the Consumer interface (found in
the java.util package) used by lists.
Lambda Expression Parameters
There are three Lambda Expression Parameters:
1.Zero Parameter

PROF. SHIV VEER SINGH (DEPARTM


2.Single Parameter
3.Multiple Parameters
1. Lambda Expression with Zero parameter

ENT OF CSE-IOT)
() -> System.out.println("Zero parameter lambda");

2. Lambda Expression with Single parameter


(p) -> System.out.println("One parameter: " + p);
3.Lambda Expression with Multiple parameters
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
Example:
• public class Main { public static void main(String[] args)
• {
• ArrayList<Integer> num = new ArrayList<Integer>();
num.add(5);
• num.add(9);

PROF. SHIV VEER SINGH (DEPARTM


• num.add(8);
• num.add(1);

ENT OF CSE-IOT)
• Consumer<Integer> method = (n) -> { System.out.println(n); };
num.forEach( method );
• }
• }
Method reference
Method reference is a special type of lambda expression. It fulfils the
purpose of a lambda expression by increasing the readability and to write a
neat code.
A method reference works in case of functional interfaces. Wherever, we are
calling a method of a functional interface with a lambda expression, we can

PROF. SHIV VEER SINGH (DEPARTM


use method reference.
Method references help to point to methods by their names even without
specifying the arguments. Arguments are passed by the lambda expression.
A method reference is described using

ENT OF CSE-IOT)
"::" symbol.
Types of Java Method References
A method reference can be used to point the
following types of methods −
1. Static methods
2. Instance methods
3. Constructors using new operator

PROF. SHIV VEER SINGH (DEPARTM


ClassName::new

ENT OF CSE-IOT)
Method Reference for Static Method
A static method can be referred using "::" symbol
easily without creating any instance of the class,
and by using class name.
Ex.
• public class MethodReference {

• public static void main(String args[]) {


• List<Integer> num = new ArrayList<>();

• num.add(3);
• num.add(6);
• num.add(2);
• num.add(7);

PROF. SHIV VEER SINGH (DEPARTM


• num.add(9);

• System.out.println("Printing using for each loop");


• // Approach 1: for loop to print all elements
• for (Integer n: num) {

ENT OF CSE-IOT)
• System.out.println(n);
• }

• System.out.println("Printing using for each loop with lambda expression");


• // Approach 2: lambda expression to print the elements in for each loop
• num.forEach(s->System.out.println(s));

• System.out.println("Printing using for each loop with method reference" );


• // Approach 3: Method reference to print elements in for each loop
• num.forEach(System.out::println);
• }
Java - Streams
• Stream represents a sequence of objects from a source, which
supports aggregate operations.
• Sequence of elements − A stream provides a set of elements of
specific type in a sequential manner. A stream gets/computes
elements on demand. It never stores the elements.

PROF. SHIV VEER SINGH (DEPARTM


• Source − Stream takes Collections, Arrays, or I/O resources as
input source.
• Aggregate operations − Stream supports aggregate operations
like filter, map, limit, reduce, find, match, and so on.

ENT OF CSE-IOT)
• Pipelining − Most of the stream operations return stream itself
so that their result can be pipelined. These operations are
called intermediate operations and their function is to take
input, process them, and return output to the target. collect()
method is a terminal operation which is normally present at the
end of the pipelining operation to mark the end of the stream.
Generating Streams in Java
• With Java 8, Collection interface has two methods to generate a
Stream.
• stream() − Returns a sequential stream considering collection as
its source.
• parallelStream() − Returns a parallel Stream considering
collection as its source.

PROF. SHIV VEER SINGH (DEPARTM


• List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
• List<String> filtered = strings.stream().filter(string -> !
string.isEmpty()).collect(Collectors.toList());

ENT OF CSE-IOT)
Important Methods for Stream API
1. forEach Method
• Stream has provided a new method 'forEach' to iterate each
element of the stream. The following code segment shows
how to print 10 random numbers using forEach.
• Example:

PROF. SHIV VEER SINGH (DEPARTM


• Random rand = new Random();
rand.ints().limit(10).forEach(System.out::println);

ENT OF CSE-IOT)
map Method
• The 'map' method is used to map each element to its
corresponding result. The following code segment prints
unique squares of numbers using map.

• Example:

PROF. SHIV VEER SINGH (DEPARTM


• List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); //get list of unique
squares List<Integer> squaresList = numbers.stream().map( i ->
i*i).distinct().collect(Collectors.toList());

ENT OF CSE-IOT)
filter Method
• The 'filter' method is used to eliminate elements based on a
criteria. The following code segment prints a count of empty
strings using filter.

• Example:

PROF. SHIV VEER SINGH (DEPARTM


• List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); //get count of
empty string

ENT OF CSE-IOT)
• int count = strings.stream().filter(string -> string.isEmpty()).count();
PROF. SHIV VEER SINGH (DEPARTM
ENT OF CSE-IOT)
Base64 Encode and Decode,
• Base64 encoding is a method to encode binary data into an
ASCII string format using a base-64 digit representation. It is
commonly used for encoding data to be sent over media that
are designed to deal with text. This ensures that the data
remains intact without modification during transport. Base64
encoding uses 64 characters (A-Z, a-z, 0-9, +, /) plus the "="

PROF. SHIV VEER SINGH (DEPARTM


padding character.
• to perform Base64 encoding and decoding in Java we use the
java.util.Base64 class:

ENT OF CSE-IOT)
• Base64 Encoding:Convert binary data (like a byte array) into a
Base64 encoded string.
• Base64 Decoding:Convert a Base64 encoded string back into
binary data (like a byte array).
Example:
• import java.util.Base64;

• public class Base64Test {

• public static void main(String[] args) {


• String input = "Hello, World!"; // input string

PROF. SHIV VEER SINGH (DEPARTM



• // Encoding the input string into Base64
• String encodedString = Base64.getEncoder().encodeToString(input.getBytes());
• System.out.println("Encoded String: " + encodedString);

ENT OF CSE-IOT)

• // Decoding the Base64 encoded string back to original string
• byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
• String decodedString = new String(decodedBytes);
• System.out.println("Decoded String: " + decodedString);
• }
• }
• Encoding:
• Base64.getEncoder().encodeToString(input.getBytes()):
• input.getBytes() converts the string input to a byte array.
• Base64.getEncoder().encodeToString(...) encodes the byte array
to a Base64 string.
• Decoding:

PROF. SHIV VEER SINGH (DEPARTM


• Base64.getDecoder().decode(encodedString):
• Base64.getDecoder().decode(...) decodes the Base64 string back
to a byte array.

ENT OF CSE-IOT)
• new String(decodedBytes) converts the byte array back to a
string.
• The Base64 class also provides methods for encoding and
decoding URLs and MIME types:
• URL Encoding and Decoding:
• Base64.getUrlEncoder()
• Base64.getUrlDecoder()
• MIME((Multipurpose Internet Mail Extensions)) Encoding and
Decoding:

PROF. SHIV VEER SINGH (DEPARTM


• Base64.getMimeEncoder()
• Base64.getMimeDecoder()

ENT OF CSE-IOT)
URL Encoding and Decoding:
• URL encoding is used to encode data that will be included in URLs. URL-
safe encoding replaces + and / with - and _ respectively to ensure the
encoded string can be safely included in a URL.

• import java.util.Base64;

• public class URLBase64Test{

PROF. SHIV VEER SINGH (DEPARTM


• public static void main(String[] args) {
• String input = "Hello, World!"; // Sample input string

• // URL-safe Base64 Encoding


• String urlEncodedString = Base64.getUrlEncoder().encodeToString(input.getBytes());

ENT OF CSE-IOT)
• System.out.println("URL Encoded String: " + urlEncodedString);

• // URL-safe Base64 Decoding


• byte[] urlDecodedBytes = Base64.getUrlDecoder().decode(urlEncodedString);
• String urlDecodedString = new String(urlDecodedBytes);
• System.out.println("URL Decoded String: " + urlDecodedString);
• }
• }
MIME Base64 Encoding and Decoding
MIME encoding is often used for email and can break the encoded output into multiple
lines.
• import java.util.Base64;

• public class MIMEBase64Test {

• public static void main(String[] args) {


• // Sample input string

PROF. SHIV VEER SINGH (DEPARTM


• String input = "Hello, World! This is a longer string to demonstrate MIME encoding.";

• // MIME Base64 Encoding


• String mimeEncodedString =
Base64.getMimeEncoder().encodeToString(input.getBytes());

ENT OF CSE-IOT)
• System.out.println("MIME Encoded String: " + mimeEncodedString);

• // MIME Base64 Decoding


• byte[] mimeDecodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
• String mimeDecodedString = new String(mimeDecodedBytes);
• System.out.println("MIME Decoded String: " + mimeDecodedString);
• }
• }
Try-with-resources
• The try-with-resources statement in Java ensures that each
resource is closed at the end of the statement. A resource is
an object that must be closed after the program is finished
with it (e.g., files, database connections).

PROF. SHIV VEER SINGH (DEPARTM


ENT OF CSE-IOT)
Type Annotations

• Type annotations can be used to annotate the use of types.
These annotations can be used on any use of a type, such as
variable declarations, type casts, and more.

PROF. SHIV VEER SINGH (DEPARTM


• Repeating Annotations

ENT OF CSE-IOT)
• Repeating annotations allow the same annotation to be
applied multiple times to a declaration or type use.
Diamond Syntax with Inner Anonymous Class

• Java 7 introduced the diamond syntax (`<>`) to reduce boilerplate code when
creating generic instances. This can also be used with inner anonymous classes.

• public class ABC {


• public static void main(String[] args) {
• List<String> list = new ArrayList<>() {

PROF. SHIV VEER SINGH (DEPARTM


• {
• add("Hello");
• add(“Java");
• }

ENT OF CSE-IOT)
• };

• for (String s : list) {
• System.out.println(s);
• }
• }
• }
Local Variable Type Inference
• Java 10 introduced the `var` keyword, which allows the
compiler to infer the type of a local variable.
• public class LocalVariableTest {
• public static void main(String[] args) {

PROF. SHIV VEER SINGH (DEPARTM


var message = "Hello, Java!";
• var number = 10;

ENT OF CSE-IOT)
• System.out.println(message);
• System.out.println(number);
Text Blocks

• Text blocks (introduced in Java 13) make it easier to write multiline
strings.
• public class TextBlocksTest{
• public static void main(String[] args) {

PROF. SHIV VEER SINGH


(DEPARTMENT OF CSE-IOT)
• String textBlock = """
• This is a text block.
• It allows for multiline strings
• without needing escape characters.
• """;

• System.out.println(textBlock);
• }
• }

You might also like