0% found this document useful (0 votes)
4 views17 pages

Java Unit 3 Notes New Fetures Part 2 Sakshiji

The document provides a comprehensive overview of various features introduced in Java 8, including default methods, functional interfaces, lambda expressions, method referencing, the Stream API, and type annotations. It also covers advanced topics like sealed classes and records, showcasing their functionalities through code examples. Additionally, it explains the use of try-with-resources and the diamond operator in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

Java Unit 3 Notes New Fetures Part 2 Sakshiji

The document provides a comprehensive overview of various features introduced in Java 8, including default methods, functional interfaces, lambda expressions, method referencing, the Stream API, and type annotations. It also covers advanced topics like sealed classes and records, showcasing their functionalities through code examples. Additionally, it explains the use of try-with-resources and the diamond operator in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

package AbhishekJava;

import java.util.*;

// Default Methods in Java 1.8

/*

interface Test

public void first();

public default void MyDefaultMethod()

System.out.println("Inside default method Test");

public static void myStaticMethod()

System.out.println("Inside static method");

public class UnitThree implements Test

public void first()

System.out.println("inside main");

public static void main(String a[])

{
UnitThree obj = new UnitThree();

obj.first();

obj.MyDefaultMethod();

Test.myStaticMethod();

//obj.myStaticMethod();

*/

/*

//functional Interface and Lambda//

//@FunctionalInterface

interface Message

//public abstract void msgA();

public abstract void Sum(int x , int y);

public class UnitThree

public static void main(String args[])

//Interface implementation using Anonymous Inner Class: - Order


Method in Java 1.7 or earlier

Message m1 = new Message()

@Override

};
m1.msgA();

//Interface implementation using Lambda Express: - New method


in Java 1.8 or later

// Message m2 = ()->System.out.println("By using Lambda


Express");

//m2.msgA();

Message m3 =(int num1, int num2) -> System.out.println("Sum of


two number is= " + (num1+num2));

m3.Sum(2,3);

*/

/* public class UnitThree

public static void main(String args[])

System.out.println("Enter any String");

Scanner sc = new Scanner(System.in);

String sample = sc.nextLine();

System.out.println("Sample String:\n"+ sample);

String encoded = Base64.getEncoder().encodeToString(sample.getBytes());

System.out.println("Encoded String:\n"+ encoded);

byte[] actualByte = Base64.getDecoder().decode(encoded);


String actualString = new String(actualByte);

System.out.println("actual String:\n" + actualString);

*/

/*

* The mapping of Function Interface method to the specified method by using “::” (double colon)

operator is called Method Referencing.

This specified method can be either a static or instance method.

But there is a condition, Functions Interface method and specified method

should have same argument types, except this the remaining things like return type,

method name, access modifier is not required to match

*/

/*

interface Sayable{

void say();

public class UnitThree {

public static void saySomething(){

System.out.println("Hello, this is static method.");

public static void ThreadStatus(){

System.out.println("Thread is running...");

public static void main(String[] args) {

// Referring static method


Sayable sayable = UnitThree::saySomething;

// Calling interface method

sayable.say();

Thread t2=new Thread(UnitThree::ThreadStatus);

t2.start();

} */

//Another example of method refrenceing

/*

import java.util.function.BiFunction;

class Arithmetic{

public static int add(int a, int b){

return a+b;

public class UnitThree {

public static void main(String[] args) {

BiFunction<Integer, Integer, Integer>adder = Arithmetic::add;

int result = adder.apply(10, 20);

System.out.println(result);

*/

/*

* Stream API is another new feature of Java 8.

* All the classes and interfaces of this Stream API is in the

java.util.stream package. By using this package,

the programmer can perform various aggregate

operations on the data returned from collections, arrays,


and I/O operations.

*/

/*

import java.util.stream.Collectors;

public class UnitThree {

public static void main (String args [])

List<Integer> li = new ArrayList<Integer> ();

li.add(10);

li.add(20);

li.add(30);

li.add(40);

List<Integer> ll =li.stream().map((x)->x*x).collect(Collectors.toList());

System.out.println("List of number are="+li);

System.out.println("Square of list of number are="+ll);

*/

/*

* import java.util.ArrayList; import java.util.List; public class UnitThree {

* public static void main(String[] args) { List<String> sList = new

* ArrayList<String>(); sList.add("Ankush"); sList.add("Akshar");

* sList.add("Archana"); sList.add("Ananya");

* System.out.println("-------You are still doing great----------");

* sList.forEach(z -> System.out.println(z));

*
*}}

*/

/*

* By this, now we don’t need to add an extra

* finally block for just passing the closing statements of the resources.

* The resources will be closed as soon as the try-catch block is executed

*/

/*

import java.io.FileOutputStream;

public class UnitThree

public static void main(String args[]){

// Using try-with-resources

try(FileOutputStream fileOutputStream =new FileOutputStream("D:/KIET/4. Even Sem 2023-


24/Subjects/2nd year OOPS with JAVA/Notes/abc.txt")){

String msg = "You all are great Students";

byte byteArray[] = msg.getBytes(); //converting string into byte array

fileOutputStream.write(byteArray);

System.out.println("You are doing good its done writing the file !");

catch(Exception exception){

System.out.println(exception);

} */

/* Java Type Annotations

* Java 8 has included two new features repeating and type annotations
* in its prior annotations topic. In early Java versions,

* you can apply annotations only to declarations.

* After releasing of Java SE 8 ,

* Java Type annotations can be applied to any type use.

* It means that annotations can be used anywhere you use a type.

* For example, if you want to avoid NullPointerException in your code,

* you can declare a string variable like this

@NonNull String str;

@NonNull List<String>

List<@NonNull String> str

Arrays<@NonNegative Integer> sort

@Encrypted File file

@Open Connection connection

*/

/*

import java.lang.annotation.Repeatable;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

@Repeatable(Games.class)

@interfaceGame{

String name();

String day();

//Declaring container for repeatable annotation type


@Retention(RetentionPolicy.RUNTIME)

@interfaceGames{

Game[] value();

//Repeating annotation

@Game(name = "Cricket", day = "Sunday")

@Game(name = "Hockey", day = "Friday")

@Game(name = "Football", day = "Saturday")

public class UnitThree {

public static void main(String[] args) {

// Getting annotation by type into an array

Game[] game = UnitThree.class.getAnnotationsByType(Game.class);

for (Gamegame2 : game) { // Iterating values

System.out.println(game2.name()+" on "+game2.day());

*/

/*

* With the help of Diamond operator, we can create an object

* without mentioning the generic type on the right hand side

* of the expression. But the problem is it will only work with

* normal classes.

* /

*/

//Program to illustrate the problem

//while linking diamond operator

//with an anonymous inner class

/*

abstract class MyMath<T> {

abstract T add(T num1, T num2);


}

public class UnitThree {

public static void main(String[] args)

MyMath<Integer> obj = new MyMath<>() {

Integer add(Integer n1, Integer n2)

return (n1 + n2);

};

Integer result = obj.add(10, 20);

System.out.println("Addition of two numbers: " + result);

} */

//Java code for local variable

//declaration using LVTI

/*

import java.util.ArrayList;

class UnitThree {

public static void main(String ap[])

var x = new ArrayList<>();

*/

/* use of yield

*/

/*
public class UnitThree

private static final int ONE = 1;

private static final int TWO = 2;

public static void main(String a[])

int number=2;

String message = switch (number) {

case ONE -> {

yield "Got a 1";

case 2 -> {

yield "Got a 2";

default -> {

yield "More than 2";

};

System.out.println("Yield ans is : "+message);

*/

//text blocks

/*

public class UnitThree

{
public static void main(String a[])

String message1 = "A-143, 9th Floor, Sovereign Corporate Tower,\n" +

"Sector-136, Noida,\n" +

"Uttar Pradesh - 201305";

//BETTER : Using text blocks

//gets rid of lots of the clutter

String message2 = """

A-143, 9th Floor, Sovereign Corporate Tower,

Sector-136, Noida,

Uttar Pradesh - 201305""";

System.out.println("Tesing Msg 1 : "+message1);

System.out.println("Tesing Msg 2 : "+message2);

*/

/*

* record

*/

/*

public class UnitThree {

public static void main(String[] args) {

EmpRecord empRecord1 = new EmpRecord(10, "Ankit", 10000, null);

EmpRecord empRecord2 = new EmpRecord(10, "Ankit", 10000, null);

// toString()
System.out.println(empRecord1);

// accessing fields

System.out.println("Name: "+empRecord1.name());

System.out.println("ID: "+empRecord1.id());

// equals()

System.out.println(empRecord1.equals(empRecord2));

// hashCode()

System.out.println(empRecord1 == empRecord2);

}*/

/*

* a sealed class is a technique that limits the number of classes

* that can

* inherit the given class.

*/

import java.lang.*;

sealed class Human permits Manish, Vartika, Anjali

public void printName()

System.out.println("Default");
}

non-sealed class Manish extends Human

public void printName()

System.out.println("Manish Sharma");

non-sealed class Vartika extends Human

public void printName()

System.out.println("Vartika Dadheech");

final class Anjali extends Human

public void printName()

System.out.println("Anjali Sharma");

class My extends Human

}
public class UnitThree

public static void main(String[] args)

Human h1 = new Anjali();

Human h2 = new Vartika();

Human h3 = new Manish();

h1.printName();

h2.printName();

h3.printName();

package AbhishekJava;
// Java Program to Illustrate Record's
functionalities
//Java Program Illustrating a Record class
//defining constructors, instance methods
//and static fields

//Record class
record Employee(int id, String firstName,
String lastName)
{

// Instance fields need to be present in the


record's
// parameters but record can define static fields.
static int empToken;

// Constructor 1 of this class


// Compact Constructor
public Employee
{
if (id < 100) {
throw new IllegalArgumentException(
"Employee Id cannot be below 100.");
}
if (firstName.length() < 2) {
throw new IllegalArgumentException(
"First name must be 2 characters or
more.");
}
}

// Constructor 2 of this class


// Alternative Constructor
public Employee(int id, String firstName)
{
this(id, firstName, null);
}

// Instance methods
public void getFullName()
{
if (lastName == null)
System.out.println(firstName());

else
System.out.println(firstName() + " "
+ lastName());
}

// Static methods
public static int generateEmployeeToken()
{
return ++empToken;
}
}
// Main class
public class MyEmp {

// Main driver method


public static void main(String args[]) {

// Creating object with default constructor


Employee e1 = new Employee(1001, "Derok",
"Dranf");
// auto generated getter methods
System.out.println(e1.id() + " " + e1.firstName()
+ " " + e1.lastName());

// Auto-generated toString() method


System.out.println(e1.toString());

// Creating object with parameterized constructor


Employee e2 = new Employee(1002, "Seren");

// Using instance methods


e2.getFullName();

// Using static methods


System.out.println("Employee " + e2.id()
+ " Token = "
+ e2.generateEmployeeToken());

// Using the equals() method


System.out.print("Is e1 equal to e2: "
+ e1.equals(e2));
}
}

You might also like