java-unit-iii-oops-with-java-unit-3-notes
java-unit-iii-oops-with-java-unit-3-notes
UNIT-III
Functional Interface:-
For Example:-
@FunctionalInterface
Interface Sayable{
public void saySomething(String msg);
}
class Doable implements Sayable
{
@Override
public void saySomething(String msg)
{
System.out.println(msg);
}
}
class TestFI
{
public static void main(String …s)
{
Doable obj=new Doable();
Obj.saySomething(“United”);
}
}
Note:
1. It is not mandatory to use @FunctionalInterface or @Override annotation to define
a functional interface.
2. Functional Interface can also contains methods from Object class like
hashCode(),toString() etc.
3. Functional Interface cannot contain user-define non-abstract method.
1. From java version 9, an interface can contain default methods as well as static methods.
2. Default method is a method with body(instructions). It is defined using “default” keyword.
3. Static method is a method defined with “static” keyword (just like in a class).
DHANANJAYSHARMAOFFICIALS
For example:-
Interface Vehicle
{
public void ignition();
public void accelerate();
public void brakes();
public void gearUp();
public void gearDown();
public applyClutch();
public releaseClutch();
public default String systemDiagnostics()
{
return “System diagnosis is in progress…”;
}
public static int getHorsePower(int rpm,int torque)
{
return ((rpm*torque)/5252);
}
}
DHANANJAYSHARMAOFFICIALS
System.out.println(“Clutch is released”);
}
}
Class Test
{
Car swift=new Car(10,2000,20);
Car nexon=new Car(11,6000,60);
Swift.systemDiagnosis();
Nexon.systemDiagnosis();
Vehicle.getHorsePower(swift.rpm,swift.torque);
Vehicle.getHorsePower(nexon.rpm,nexon.torque);
Explanation: In the above program, a Vehicle interface is defined with some abstract
methods, default method and static method. Since every Car have its own operating mechanism like
transmission system, etc so they are defined as abstract so every car defines its own implementation
but it may be possible that car diagnosis system is same so it is defined using “default” keyword so
every car need not to give its own implementation. Similarly, a utility task of fetching car’s horse
power is defined as static method. Any car can use this utility function as they need.
Lambda Expression:-
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.
DHANANJAYSHARMAOFFICIALS
No Parameter Syntax
() -> {
//Body of no parameter lambda
}
(p1) -> {
//Body of single parameter lambda
}
(p1,p2) -> {
//Body of multiple parameter lambda
}
Example 1:-
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
DHANANJAYSHARMAOFFICIALS
Example 2:
interface Sayable{
public String say(String name);
}
Method Reference:-
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.
DHANANJAYSHARMAOFFICIALS
DHANANJAYSHARMAOFFICIALS
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Stream API
DHANANJAYSHARMAOFFICIALS
• Intermediate Operations
• Terminate Operations
1. No Storage
2. Pipeline of Functions
3. Laziness
4. Can be infinite
5. Can be parallelized
6. Can be created from collections, arrays, Files Lines, Methods in Stream,
IntStream etc.
DHANANJAYSHARMAOFFICIALS
1. map()
The map method is used to return a stream consisting of the results of
applying the given function to the elements of this stream.
2. filter()
The filter method is used to select elements as per the Predicate passed as an
argument.
3. sorted()
The sorted method is used to sort the stream.
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.
1. collect()
The collect method is used to return the result of the intermediate operations
performed on the stream.
DHANANJAYSHARMAOFFICIALS
2. forEach()
The forEach method is used to iterate through every element of the stream.
3. reduce()
The reduce method is used to reduce the elements of a stream to a single
value. The reduce method takes a BinaryOperator as a parameter.
Base64 encoding allows encoding binary data as text strings for safe transport,
at the cost of larger data size. It is commonly used when there is a need to
encode binary data that needs to be stored or transferred via media that are
designed to deal with textual data (like transporting images inside an XML,
JSON document, etc.).
DHANANJAYSHARMAOFFICIALS
DHANANJAYSHARMAOFFICIALS
DHANANJAYSHARMAOFFICIALS
// Encoding string
String str = encoder.encodeToString("UNITED".getBytes());
System.out.println("Encoded string: "+str);
// Getting decoder
Base64.Decoder decoder = Base64.getDecoder();
// Decoding string
String dStr = new String(decoder.decode(str));
System.out.println("Decoded string: "+dStr);
}
}
Output:
DHANANJAYSHARMAOFFICIALS
Output:
DHANANJAYSHARMAOFFICIALS
You can pass any object that implements java.lang.AutoCloseable, which includes all
objects which implement java.io.Closeable.
Try-with-resources Example 1
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 United!";
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);
}
}
}
Output:
Welcome to United!
DHANANJAYSHARMAOFFICIALS
• Module name
• What does it export
• What does it require
Creating the java modules involves three steps to be created in java. The three
steps to be followed are:
Local variable type inference is a feature in Java 10 that allows the developer
to skip the type declaration associated with local variables (those defined
inside method definitions, initialization blocks, for-loops, and other blocks like
if-else), and the type is inferred by the JDK. It will, then, be the job of the
compiler to figure out the datatype of the variable.
DHANANJAYSHARMAOFFICIALS
import java.util.ArrayList;
import java.util.List;
class A {
public static void main(String ap[])
{
var data = new ArrayList<>();
}
}
switch (itemCode) {
case 001, 002, 003 :
System.out.println("It's an electronic gadget!");
break;
DHANANJAYSHARMAOFFICIALS
• Statement / expression
• throw statement
• {} block
The main advantage of this syntax is that we don’t need a break statement to
avoid the default fall-through. So, the rule is, if we need fall-through, use case:
else if not use case ⇾. Also note, for all case branches it should be either case:
or case ⇾. It cannot be different or different cases in a switch else it results in
an error.
switch (itemCode) {
case 001 -> System.out.println("It's a laptop!");
case 002 -> System.out.println("It's a desktop!");
case 003,004 -> System.out.println("It's a mobile phone!");
}
DHANANJAYSHARMAOFFICIALS
6. Scope: The variables declared in the traditional switch exists until the
end of the switch statement. If we want the variables to have a case
level scope, we can use {} introduced by the enhanced switch in Java 13.
switch (errorCode) {
case 101: {
// This variable exists just in this {} block
int num = 200;
break;
}
case 300: {
// This is ok, {} block has a separate scope
int num = 300;
}
}
The object created from text blocks is java.lang.String with the same
properties as a regular string enclosed in double quotes.
DHANANJAYSHARMAOFFICIALS
Records in java
In Java, a record is a special type of class declaration aimed at reducing
the boilerplate code. Java records were introduced with the intention to
be used as a fast way to create data carrier classes, i.e. the classes
whose objective is to simply contain data and carry it between modules,
also known as POJOs (Plain Old Java Objects) and DTOs (Data Transfer
Objects).
DHANANJAYSHARMAOFFICIALS
// Setter-getter Method 1
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
// Setter-getter Method 2
// to get the first name of employee
public String getFirstName() { return firstName; }
// Setter-getter Method 3
// To set the last name of employees
public void setLastName(String lasstName)
{
// Setter-getter Method 3
// To set the last name of employees
public String getLastName() { return lastName; }
// Setter-getter Method 4
// To set the last name of employees
public void setId(int Id) { this.Id = Id; }
// Setter-getter Method 5
// To set the last name of employees
public int getId() { return Id; }
// Setter-getter Method 6
public String toString()
{
DHANANJAYSHARMAOFFICIALS
// Method 7
// Overriding hashCode method
@Override public int hashCode()
{
// Final variable
final int prime = 31;
int result = 1;
return result;
}
// Method 8
// Overriding equals method to
// implement with data structures
@Override public boolean equals(Object obj)
{
DHANANJAYSHARMAOFFICIALS
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (Id != other.Id)
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
}
else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
}
else if (!lastName.equals(other.lastName))
return false;
return true;
}
}
Now let’s look at what it would take to create a similar class using
Record.
That’s it!
DHANANJAYSHARMAOFFICIALS
Sealed class is a technique that limits the number of classes that can
inherit the given class. This means that only the classes designated by
the programmer can inherit from that particular class, thereby
restricting access to it. when a class is declared sealed, the programmer
must specify the list of classes that can inherit it. The concept of sealed
classes in Java was introduced in Java 15.
DHANANJAYSHARMAOFFICIALS
• @NonNull List<String>
• List<@NonNull String> str
• Arrays<@NonNegative Integer> sort
• @Encrypted File file
• @Open Connection connection
• void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException
DHANANJAYSHARMAOFFICIALS
Cricket on Sunday
Hockey on Friday
Football on Saturday
DHANANJAYSHARMAOFFICIALS