0% found this document useful (0 votes)
8 views46 pages

Java Lab Manual

The document outlines the curriculum for the Object Oriented Programming with Java Lab (BCS-452) for the 4th semester at the United Institute of Technology, detailing the department's vision, mission, course objectives, outcomes, and prerequisites. It includes general laboratory instructions and a comprehensive list of experiments to be conducted, focusing on various Java programming concepts such as OOP, exception handling, multithreading, and the Spring framework. The document serves as a guide for students to prepare for their lab sessions and complete the required experiments.

Uploaded by

a84873761
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)
8 views46 pages

Java Lab Manual

The document outlines the curriculum for the Object Oriented Programming with Java Lab (BCS-452) for the 4th semester at the United Institute of Technology, detailing the department's vision, mission, course objectives, outcomes, and prerequisites. It includes general laboratory instructions and a comprehensive list of experiments to be conducted, focusing on various Java programming concepts such as OOP, exception handling, multithreading, and the Spring framework. The document serves as a guide for students to prepare for their lab sessions and complete the required experiments.

Uploaded by

a84873761
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

UNITED INSTITUTE OF TECHNOLOGY (284)

NAINI, PRAYAGRAJ

(Affiliated to Dr. A.P.J Abdul Kalam Technical University, Lucknow)

OBJECT ORIENTED PROGAMMING


WITH
JAVA LAB (BCS-452)
For

4th SEMESTER

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


(SESSION 2023-2024)

Amit Dubey
NAME: ……………………………………………………………………………

2402841540005
ROLL NO: ………………………………………………………………………..

CS(DS) / IVTH / 2G
BRANCH/SEM/SEC: ……………………………………………………………………………
Vision of the Department

To be a center of excellence in the field of Computer Science and Engineering for


producing talented engineers to ethically serve constantly changing needs of society and
industry throughout their career and life.

Mission of the Department


M1. Accomplish excellence with committed faculty by providing theoretical
foundation and practical skills for solving complex engineering problems in the
state-of-the-art trends in Computer science and allied disciplines.
M2. To foster skills and competency, generating novel ideas, entrepreneurship and
model creations focused towards deep knowledge, interpersonal skills and
leadership.
M3. To develop habitude of research among faculty and students in the area of
Computer Science & Allied disciplines by providing the desired environment, for
addressing the needs of industry and society.

M4. To would the students with ethical principles in thoughts, expression and deeds.
Course Objectives
S. No. Statements

1. To provide an understanding of the design aspects of program using OOPS


2. To Understand Exception Handling, Multi-Threading, I/O

3. To understand the concept of Functional Interface,Stream API


4. To understand the purpose and need of Collection Interface

5 To understand Spring framework and Spring Boot framework.

Course Outcomes (COs)


COs CO Statements Knowledge
Level
CO1 To implement the core concepts of OOPs with Java with basic K1,K2
CO2 To implement the concepts of Exception-handling, Multi-Threading and K2,K2
I/O
CO3 To implement the concepts of Functional Interface K1,K2
CO4 To implement the concepts of Collection Framework K1,K2

CO5 To implement the concept of RESTful API using Spring Boot K1,K2

Course Prerequisites
Student should know the implements of C programming language.
Student should know the mechanism of linking, loading, compilation, execution of a program
General laboratory instructions

1. Students are advised to come to the laboratory at least 5 minutes before (to starting time),
those who come after 5 minutes will not be allowed into the lab.

2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis/ program / experiment details.

3. Student should enter into the laboratory with: a. Laboratory observation notes with all the
details (Problem statement, Aim, Algorithm, Procedure, Program, Expected Output, etc.,) filled
in for the lab session. b. Laboratory Record updated up to the last session experiments and
other utensils (if any) needed in the lab. c. Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.

5. Execute your task in the laboratory, and record the results / output in the lab observation note
book, and get certified by the concerned faculty.

6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.

7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.

8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviours with the staff and systems etc., will attract
severe punishment.

9. Students must take the permission of the faculty in case of any urgency to go out ; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.

10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly.
INDEX

[Link] List of Experiments Page Date Faculty Remarks


No. Sign
1 Basics of Java Programming: 02/02/2026
Program to check whether a number is Peterson
Number or Not
2 Program to check whether a number is 02/02/2026
Automorphic Number or Not

3 Program to check whether a number is 09/02/2026


Trimorphic Number or Not

4 Program to check whether a number is 09/02/2026


Disarium Number.

5 Program to check whether a number is Evil or 10/02/2026


Odious

6 OOPs Concept: 10/02/2026


Create a Class BankAccount with
constructor:
non-parameterized,
parameterized,
copy
state:
accountNumber,
accountHolderName,
balance
behaviors:
deposit,
withdraw,
checkBalance
7 Create a class Employee with static and 16/02/2026
non-static fields. Show how static fields
behave across objects

8 Given a base class Animal with a method 16/02/2026


walk(), and a derived class Bird that already
includes a method fly(), use inheritance to
enhance the Bird class by adding a new
method sing(). Then, modify the main
method to create a Bird object and call all
three methods (walk(), fly(), and sing()), so
that the program outputs:
I am walking
I am flying
I am singing

9 You are given an abstract class Book that 17/02/2026


contains a field title, an abstract method
setTitle(String s), and a concrete method
getTitle().
Create a subclass MyBook that extends
Book. Implement the abstract method
setTitle(String s) to assign the given string
to the title field.
In the provided Main class, an object of
MyBook is created. Your implementation
should ensure that when a title is provided as
input, the program outputs:
The title is: <input_title>

10 You are given a base class Sports with 17/02/2026


methods getName() and
getNumberOfTeamMembers(). A subclass
Soccer extends Sports and overrides the
getName() method.
Your task is to further override the
getNumberOfTeamMembers() method in
the Soccer class so that it prints the same
message as the superclass method, but
replaces the generic number of players (n)
with 11, which is the number of players in a
soccer team.
When the program runs, it should output:
Generic Sports
Each team has n players in Generic
Sports
Soccer Class
Each team has 11 players in Soccer Class

11 Java Package: 23/02/2026


Create a package mathlib with a class
MathTools containing methods factorial(int)
and isPrime(int). Use it in the main program
12 Exception: 23/02/2026
Write a program to handle multiple
exceptions (NullPointerException,
NumberFormatException) in a single try
block.
13 You are given two inputs that are expected 24/02/2026
to be 32-bit signed integers, a and b. Your
task is to compute the result of integer
division a / b using Java's exception
handling mechanism.
Use a try-catch block to handle possible
exceptions that may occur in the following
cases:
 If the inputs are not valid integers, an
InputMismatchException should be
caught.
 If division by zero occurs (b = 0), an
ArithmeticException should be
caught.
14 MultiThreading: 24/02/2026
Create a multithreading program where two
threads print numbers from 1 to 10, but with
one-second delay using [Link]().

15 Create a multithreading program to 16/03/2026


demonstrate Thread synchronization.

16 Create a multithreading program to get and 16/03/2026


set Thread priority.

17 Create a multithreading program to 17/03/2026


demonstrate Inter Thread Communication
using wait() and notify().
18 Input/Output: 17/03/2026
Write a program to accept Person’s name,
contact and address from user and save it
into file.
19 Write a program to copy content of a file 17/03/2026
and paste it into another file.

20 Define a functional interface Calculator 23/03/2026


with a method operate(int a, int b).
Write lambda expressions to perform
addition, subtraction, and multiplication
using this interface.
21 Stream API & forEach Method 23/03/2026
Given a list of integers, use the Stream API
to:
 Filter even numbers
 Square them
 Print the results using forEach

22 ArrayList & Iterator 23/03/2026


Write a Java program to:
 Create an ArrayList of integers
 Add at least 10 elements
 Use an Iterator to remove all even
numbers
 Print the remaining elements

23 LinkedList as Queue 30/03/2026


Write a program to:
 Create a LinkedList and use it as a
Queue
 Add 5 elements
 Remove elements one by one using
queue methods (poll)
 Display the elements as they are
removed

24 HashSet & LinkedHashSet 30/03/2026


Write a program to:
 Store a list of duplicate strings in
both HashSet and LinkedHashSet
 Print both sets and observe the
difference in ordering

25 TreeMap Sorting 30/03/2026


Write a program to:
 Create a TreeMap of student names
and marks
 Display the map sorted by student
names
 Then sort the entries by marks using
a Comparator

26 Comparable & Comparator 06/04/2026


Create a class Student with fields id, name,
and marks.
 Implement Comparable to sort
students by id
 Use a Comparator to sort students by
marks
 Display both sorted lists

27 Dependency Injection & Bean 06/04/2026


Configuration
Create a Spring application that
demonstrates Dependency Injection using
annotations.
 Define a Service class and a
Repository class
 Inject the repository into the service
using @Autowired
 Configure beans using Java-based
configuration

28 Bean Scopes & Lifecycle Callbacks 07/04/2026


Write a Spring program to:
 Create two beans with singleton and
prototype scopes
 Demonstrate the difference by
fetching them multiple times
 Implement lifecycle callbacks using
@PostConstruct and @PreDestroy

29 RESTful Web Services (CRUD APIs) 07/04/2026


Build a Spring Boot REST API for a Student
entity:
 Implement endpoints for GET,
POST, PUT, and DELETE
 Use @RestController,
@RequestMapping, @PathVariable,
and @RequestBody
 Store data in a simple in-memory list
Experiment – 1
Aim -: Basics of Java Programming Program to check whether a number is Peterson Number
or Not

import [Link];

public class PetersonNumber {

static int factorial(int n) {


int fact = 1;
for(int i = 1; i <= n; i++) {
fact = fact * i;
}
return fact;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

int temp = num;


int sum = 0;

while(temp > 0) {
int digit = temp % 10;
sum = sum + factorial(digit);
temp = temp / 10;
}

if(sum == num) {
[Link](num + " is a Peterson Number.");
} else {
[Link](num + " is NOT a Peterson Number.");
}

[Link]();
}
}
Experiment -2
Aim-: Program to check whether a number is Automorphic Number or Not

import [Link];

public class AutomorphicNumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

int square = num * num;


int temp = num;

boolean isAutomorphic = true;

while (temp > 0) {


if (temp % 10 != square % 10) {
isAutomorphic = false;
break;
}
temp = temp / 10;
square = square / 10;
}

if (isAutomorphic) {
[Link](num + " is an Automorphic Number.");
} else {
[Link](num + " is NOT an Automorphic Number.");
}

[Link]();
}
}
Experiment – 3
Aim -: Program to check whether a number is Trimorphic Number or Not

import [Link];

class TrimorphicNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
int cube = num * num * num;
int temp = num;
boolean isTrimorphic = true;
while (temp > 0) {
if (temp % 10 != cube % 10) {
isTrimorphic = false;
break;
}
temp = temp / 10;
cube = cube / 10;
}
if (isTrimorphic) {
[Link](num + " is a Trimorphic Number.");
} else {
[Link](num + " is NOT a Trimorphic Number.");
}
[Link]();
}
}
Experiment – 4
Aim -: Program to check whether a number is Disarium Number
import [Link];

class DisariumNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
int temp = num;
int count = 0;
while (temp > 0) {
count++;
temp = temp / 10;
}
temp = num;
int sum = 0;
while (temp > 0) {
int digit = temp % 10;
sum += [Link](digit, count);
count--;
temp = temp / 10;
}
if (sum == num) {
[Link](num + " is a Disarium Number.");
} else {
[Link](num + " is NOT a Disarium Number.");
}
[Link]();
}
}
Experiment – 5
Aim -: Program to check whether a number is Evil or Odious
import [Link];

class EvilOdious {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

int temp = num;


int count = 0;

// Count number of 1's in binary


while (temp > 0) {
if (temp % 2 == 1) {
count++;
}
temp = temp / 2;
}

if (count % 2 == 0) {
[Link](num + " is an Evil Number.");
} else {
[Link](num + " is an Odious Number.");
}

[Link]();
}
}
Experiment – 6
Aim - : OOPs Concept:Create a Class BankAccount with
constructor: non-parameterized, parameterized, copy
state: accountNumber, accountHolderName, balance
behclass BankAccount {

int accountNumber;
String accountHolderName;
float balance;

BankAccount() {
accountNumber = 0;
accountHolderName = "Not Assigned";
balance = 0;
}

BankAccount(int accNo, String name, float bal) {


accountNumber = accNo;
accountHolderName = name;
balance = bal;
}

BankAccount(BankAccount obj) {
accountNumber = [Link];
accountHolderName = [Link];
balance = [Link];
}

void deposit(float amount) {


balance += amount;
[Link]("Deposited: " + amount);
}

void withdraw(float amount) {


if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Insufficient Balance!");
}
}

void checkBalance() {
[Link]("Account Number: " + accountNumber);
[Link]("Account Holder: " + accountHolderName);
[Link]("Balance: " + balance);
}
}

class Main {
public static void main(String[] args) {

BankAccount acc1 = new BankAccount();


[Link]();
BankAccount acc2 = new BankAccount(101, "Amit", 5000);
[Link](2000);
[Link](1000);
[Link]();

BankAccount acc3 = new BankAccount(acc2);


[Link]();
}
}
aviors: deposit, withdraw, checkBalance
Experiment – 7
Aim - : Create a class Employee with static and non-static fields. Show how static fields behave
across objects
class Employee {
static String companyName = "Being Human Pvt. Ltd.";
int empId;
String empName;
Employee(int id, String name) {
empId = id;
empName = name;
}
void display() {
[Link]("Employee ID: " + empId);
[Link]("Employee Name: " + empName);
[Link]("Company Name: " + companyName);
[Link]();
}
}
class Main {
public static void main(String[] args) {
Employee e1 = new Employee(101, "Amit");
Employee e2 = new Employee(102, "Yash");
[Link]("Before changing static field:");
[Link]();
[Link]();
[Link] = "We are I pvt. Ltd.";
[Link]("After changing static field:");
[Link]();
[Link]();
}
}
Experiment – 8
Aim -: Given a base class Animal with a method walk(), and a derived class Bird that already
includes a method fly(), use inheritance to enhance the Bird class by adding a new method sing().
Then, modify the main method to create a Bird object and call all three methods (walk(), fly(), and
sing()), so that the program outputs:
I am walking
I am flying
I am singing

// Base Class
class Animal {
void walk() {
[Link]("I am walking");
}
}

class Bird extends Animal {


void fly() {
[Link]("I am flying");
}

void sing() {
[Link]("I am singing");
}
}

class Main {
public static void main(String[] args) {
Bird b = new Bird();

[Link](); // from Animal class


[Link](); // from Bird class
[Link](); // newly added method
}
}
Experiment – 9
Aim - : You are given an abstract class Book that contains a field title, an abstract method
setTitle(String s), and a concrete method getTitle().
Create a subclass MyBook that extends Book. Implement the abstract method setTitle(String s) to
assign the given string to the title field.
In the provided Main class, an object of MyBook is created. Your implementation should ensure that
when a title is provided as input, the program outputs:
The title is: <input_title>

import [Link];
// Abstract Class
abstract class Book {
String title;
abstract void setTitle(String s);
String getTitle() {
return title;
}
}
class MyBook extends Book {

void setTitle(String s) {
title = s;
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("input title:");
String title = [Link]();
MyBook newBook = new MyBook();
[Link](title);
[Link]("The title is: " + [Link]());
[Link]();
}
}
Experiment – 10
Aim - : You are given a base class Sports with methods getName() and
getNumberOfTeamMembers(). A subclass Soccer extends Sports and overrides the getName()
method.
Your task is to further override the getNumberOfTeamMembers() method in the Soccer class so
that it prints the same message as the superclass method, but replaces the generic number of players
(n) with 11, which is the number of players in a soccer team.
When the program runs, it should output:
Generic Sports
Each team has n players in Generic Sports
Soccer Class
Each team has 11 players in Soccer Class

class Sports {
String getName() {
return "Generic Sports";
}
String getNumberOfTeamMembers() {
return "Each team has n players in " + getName();
}
}
class Soccer extends Sports {
String getName() {
return "Soccer Class";
}
String getNumberOfTeamMembers() {
return "Each team has 11 players in " + getName();
}
}
class Main {
public static void main(String[] args) {
Sports s = new Sports();
[Link]([Link]());
[Link]([Link]());
Soccer sc = new Soccer();
[Link]([Link]());
[Link]([Link]());
}
}
Experiment – 11
Aim - : Java Package:
Create a package mathlib with a class MathTools containing methods factorial(int) and isPrime(int).
Use it in the main program

import [Link];

class Main {
public static void main(String[] args) {

MathTools mt = new MathTools();

int num = 5;

[Link]("Factorial of " + num + " is: " + [Link](num));

if([Link](num)) {
[Link](num + " is a Prime Number.");
} else {
[Link](num + " is NOT a Prime Number.");
}
}
}
Experiment -12
Aim -:Exception:
Write a program to handle multiple exceptions (NullPointerException, NumberFormatException) in a
single try block.

class MultipleException {
public static void main(String[] args) {

try {
String str = null;
[Link]("Length: " + [Link]());

String numStr = "abc";


int num = [Link](numStr);
[Link]("Number: " + num);

} catch (NullPointerException e) {
[Link]("NullPointerException caught: String is null.");

} catch (NumberFormatException e) {
[Link]("NumberFormatException caught: Invalid number
format.");
}

[Link]("Program continues...");
}
}
Experiment – 13
Aim - : You are given two inputs that are expected to be 32-bit signed integers, a and b. Your task is
to compute the result of integer division a / b using Java's exception handling mechanism.
Use a try-catch block to handle possible exceptions that may occur in the following cases:
 If the inputs are not valid integers, an InputMismatchException should be caught.
 If division by zero occurs (b = 0), an ArithmeticException should be caught.

import [Link];
import [Link];
class Exp13 {
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

try {
[Link]("Enter value of a: ");
int a = [Link]();

[Link]("Enter value of b: ");


int b = [Link]();

int result = a / b;

[Link]("Result: " + result);

} catch (InputMismatchException e) {
[Link]("InputMismatchException: Please enter valid
integers.");

} catch (ArithmeticException e) {
[Link]("ArithmeticException: Division by zero is not
allowed.");
}

[Link]();
}
}
Experiment – 14
Aim - : MultiThreading:
Create a multithreading program where two threads print numbers from 1 to 10, but with one-second
delay using [Link]().

class MyThread extends Thread {

String threadName;

MyThread(String name) {
threadName = name;
}

public void run() {


try {
for (int i = 1; i <= 10; i++) {
[Link](threadName + ": " + i);
[Link](1000); // 1 second delay
}
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
}
class Main {
public static void main(String[] args) {

MyThread t1 = new MyThread("Thread 1");


MyThread t2 = new MyThread("Thread 2");

[Link](); // start thread 1


[Link](); // start thread 2
}
}
Experiment – 15
Aim -: Create a multithreading program to demonstrate Thread synchronization

class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}
class MyThread extends Thread {
Counter c;
MyThread(Counter c) {
this.c = c;
}
public void run() {
for (int i = 1; i <= 1000; i++) {
[Link]();
}
}
}
class Main {
public static void main(String[] args) {
Counter c = new Counter();
MyThread t1 = new MyThread(c);
MyThread t2 = new MyThread(c);
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Final Count: " + [Link]);
}
}
Experiment – 16
Aim - : Create a multithreading program to get and set Thread priority

class MyThread extends Thread {

MyThread(String name) {
super(name); // set thread name
}
public void run() {
[Link]("Running: " + getName() +
" | Priority: " + getPriority());
}
}
class Main {
public static void main(String[] args) {

MyThread t1 = new MyThread("Thread 1");


MyThread t2 = new MyThread("Thread 2");
MyThread t3 = new MyThread("Thread 3");
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10
[Link]();
[Link]();
[Link]();
}
}
Experiment – 17
Aim - : Create a multithreading program to demonstrate Inter Thread Communication using wait()
and notify().
// Shared resource
class Data {
int value;
boolean available = false;

synchronized void produce(int val) {


try {
while (available) {
wait(); // wait if data is already available
}
value = val;
[Link]("Produced: " + value);
available = true;
notify();
} catch (InterruptedException e) {
[Link](e);
}
}

synchronized void consume() {


try {
while (!available) {
wait(); // wait if no data
}
[Link]("Consumed: " + value);
available = false;
notify();
} catch (InterruptedException e) {
[Link](e);
}
}
}
class Producer extends Thread {
Data d;
Producer(Data d) {
this.d = d;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
}
class Consumer extends Thread {
Data d;
Consumer(Data d) {
this.d = d;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]();
}
}
}
class Exp17 {
public static void main(String[] args) {

Data d = new Data();

Producer p = new Producer(d);


Consumer c = new Consumer(d);

[Link]();
[Link]();
}
}
Experiment – 18
Aim -: Input/Output:
Write a program to accept Person’s name, contact and address from user and save it into file.
import [Link];
import [Link];
import [Link];
class WritePersonData {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Contact: ");
String contact = [Link]();
[Link]("Enter Address: ");
String address = [Link]();
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Name: " + name + "\n");
[Link]("Contact: " + contact + "\n");
[Link]("Address: " + address + "\n");
[Link]();
[Link]("Data saved successfully in [Link]");
} catch (IOException e) {
[Link]("Error writing to file.");
}
[Link]();
}
}
Experiment – 19
Aim -: Write a program to copy content of a file and paste it into another file.

import [Link];
import [Link];
import [Link];

class FileCopy {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("[Link]");

FileOutputStream fout = new FileOutputStream("[Link]");

int ch;

while ((ch = [Link]()) != -1) {


[Link](ch);
}
[Link]();
[Link]();

[Link]("File copied successfully.");


} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
Experiment – 20
Aim - : Define a functional interface Calculator with a method operate(int a, int b).
Write lambda expressions to perform addition, subtraction, and multiplication using this interface

interface Calculator {
int operate(int a, int b);
}
class Main1
{
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator sub = (a, b) -> a - b;
Calculator mul = (a, b) -> a * b;

int x = 10, y = 5;

[Link]("Addition: " + [Link](x, y));


[Link]("Subtraction: " + [Link](x, y));
[Link]("Multiplication: " + [Link](x, y));
}
}
Experiment – 21
Aim - : Stream API & forEach Method
Given a list of integers, use the Stream API to:
 Filter even numbers
 Square them
 Print the results using forEach

import [Link];
import [Link];

class StreamExample {

public static void main(String[] args) {

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);

[Link]()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.forEach(n -> [Link](n));

}
Experiment – 22
Aim -:ArrayList & Iterator
Write a Java program to:
 Create an ArrayList of integers
 Add at least 10 elements
 Use an Iterator to remove all even numbers
 Print the remaining elements

import [Link];
import [Link];

class ArrayListIteratorExample {
public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();


[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link](6);
[Link](7);
[Link](8);
[Link](9);
[Link](10);
Iterator<Integer> it = [Link]();
while ([Link]()) {
int num = [Link]();
if (num % 2 == 0) {
[Link]();
}
}
[Link]("Remaining elements:");
for (int n : list) {
[Link](n + " ");
}
}
}
Experiment – 23
Aim - : LinkedList as Queue
Write a program to:
• Create a LinkedList and use it as a Queue
• Add 5 elements
• Remove elements one by one using queue methods (poll)
• Display the elements as they are removed

import [Link];
import [Link];

class QueueExample {
public static void main(String[] args) {

Queue<Integer> queue = new LinkedList<>();

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

[Link]("Removing elements from queue:");


while (![Link]()) {
int removed = [Link]();
[Link](removed);
}
}
}
Experiment – 24
Aim - : HashSet & LinkedHashSet
Write a program to:
 Store a list of duplicate strings in both HashSet and LinkedHashSet
 Print both sets and observe the difference in ordering

import [Link];
import [Link];

class SetExample {
public static void main(String[] args) {

String[] data = {"Apple", "Banana", "Mango", "Apple", "Orange",


"Banana"};

HashSet<String> hashSet = new HashSet<>();

LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();

for (String s : data) {


[Link](s);
[Link](s);
}

[Link]("HashSet:");
[Link](hashSet);

[Link]("LinkedHashSet:");
[Link](linkedHashSet);
}
}
Experiment – 25
Aim - : TreeMap Sorting
Write a program to:
• Create a TreeMap of student names and marks
• Display the map sorted by student names
• Then sort the entries by marks using a Comparator

import [Link].*;

class TreeMapSorting {
public static void main(String[] args) {

TreeMap<String, Integer> students = new TreeMap<>();

[Link]("Amit", 85);
[Link]("Yash", 90);
[Link]("Abhinav", 75);
[Link]("Swastika", 95);
[Link]("Ashutosh", 80);

[Link]("Sorted by Student Names:");


for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}

List<[Link]<String, Integer>> list = new


ArrayList<>([Link]());

[Link](list, new Comparator<[Link]<String, Integer>>() {


public int compare([Link]<String, Integer> e1, [Link]<String,
Integer> e2) {
return [Link]().compareTo([Link]());
}
});

[Link]("\nSorted by Marks:");
for ([Link]<String, Integer> entry : list) {
[Link]([Link]() + " : " + [Link]());
}
}
}
Experiment – 26
Aim - : Comparable & Comparator
Create a class Student with fields id, name, and marks.
 Implement Comparable to sort students by id
 Use a Comparator to sort students by marks
 Display both sorted lists

import [Link].*;

class Student implements Comparable<Student> {


int id;
String name;
int marks;

Student(int id, String name, int marks) {


[Link] = id;
[Link] = name;
[Link] = marks;
}

public int compareTo(Student s) {


return [Link] - [Link];
}

public String toString() {


return id + " " + name + " " + marks;
}
}

class MarksComparator implements Comparator<Student> {


public int compare(Student s1, Student s2) {
return [Link] - [Link];
}
}
class Main {
public static void main(String[] args) {

List<Student> list = new ArrayList<>();

[Link](new Student(3, "Amit", 85));


[Link](new Student(1, "Yash", 90));
[Link](new Student(5, "Abhinav", 75));
[Link](new Student(2, "Swastika", 95));
[Link](new Student(4, "Ashutosh", 80));

[Link](list);
[Link]("Sorted by ID:");
for (Student s : list) {
[Link](s);
}

[Link](list, new MarksComparator());


[Link]("\nSorted by Marks:");
for (Student s : list) {
[Link](s);
}
}
}
Experiment – 27
Aim - : Dependency Injection & Bean Configuration
Create a Spring application that demonstrates Dependency Injection using annotations.
 Define a Service class and a Repository class
 Inject the repository into the service using @Autowired
 Configure beans using Java-based configuration

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Repository
class UserRepository {

public void saveUser() {


[Link]("User saved in database.");
}
}@Service
class UserService {

@Autowired
private UserRepository userRepository;

public void processUser() {


[Link]("Processing user...");
[Link]();
}
}@Configuration
@ComponentScan(basePackages = "[Link]")
class AppConfig {

public AppConfig() {
}
}
Experiment – 28
Aim - : Bean Scopes & Lifecycle Callbacks
Write a Spring program to:
 Create two beans with singleton and prototype scopes
 Demonstrate the difference by fetching them multiple times
 Implement lifecycle callbacks using @PostConstruct and @PreDestroy

import [Link];
import [Link];
import [Link];
import [Link];

@Component
@Scope("singleton")
class SingletonBean {

public SingletonBean() {
[Link]("SingletonBean Constructor Called");
}

@PostConstruct
public void init() {
[Link]("SingletonBean Initialized");
}

@PreDestroy
public void destroy() {
[Link]("SingletonBean Destroyed");
}
}@Component
@Scope("prototype")
class PrototypeBean {

public PrototypeBean() {
[Link]("PrototypeBean Constructor Called");
}

@PostConstruct
public void init() {
[Link]("PrototypeBean Initialized");
}

@PreDestroy
public void destroy() {
[Link]("PrototypeBean Destroyed");
}
}@Configuration
@ComponentScan(basePackages = "[Link]")
class AppConfig {
} class MainApp {
public static void main(String[] args) {

AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext([Link]);

SingletonBean s1 = [Link]([Link]);
SingletonBean s2 = [Link]([Link]);

[Link]("Singleton objects same? " + (s1 == s2));

PrototypeBean p1 = [Link]([Link]);
PrototypeBean p2 = [Link]([Link]);

[Link]("Prototype objects same? " + (p1 == p2));

[Link]();
}
}
Experiment - 29
Aim -: RESTful Web Services (CRUD APIs)
Build a Spring Boot REST API for a Student entity:
 Implement endpoints for GET, POST, PUT, and DELETE
 Use @RestController, @RequestMapping, @PathVariable, and @RequestBody
Store data in a simple in-memory list

package [Link];
import [Link];
import [Link];
import [Link].*;
import [Link].*;

class Student {
private long id;
private String name;
private int marks;

public Student() {}

public Student(long id, String name, int marks) {


[Link] = id;
[Link] = name;
[Link] = marks;
}

public long getId() { return id; }


public void setId(long id) { [Link] = id; }

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public int getMarks() { return marks; }


public void setMarks(int marks) { [Link] = marks; }
}@RestController
@RequestMapping("/api/students")
class StudentController {

private List<Student> students = new ArrayList<>();


private long nextId = 1;
@GetMapping
public List<Student> getAllStudents() {
return students;
}
@PostMapping
public Student createStudent(@RequestBody Student student) {
[Link](nextId++);
[Link](student);
return student;
}
@PutMapping("/{id}")
public Student updateStudent(@PathVariable long id, @RequestBody Student updatedStudent) {
for (Student s : students) {
if ([Link]() == id) {
[Link]([Link]());
[Link]([Link]());
return s;
}
}
return null;
}
@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable long id) {
[Link](s -> [Link]() == id);
return "Student deleted with id: " + id;
}
}@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

You might also like