Java Lab Manual
Java Lab Manual
NAINI, PRAYAGRAJ
4th SEMESTER
Amit Dubey
NAME: ……………………………………………………………………………
2402841540005
ROLL NO: ………………………………………………………………………..
CS(DS) / IVTH / 2G
BRANCH/SEM/SEC: ……………………………………………………………………………
Vision of the Department
M4. To would the students with ethical principles in thoughts, expression and deeds.
Course Objectives
S. No. Statements
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
import [Link];
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];
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]);
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(BankAccount obj) {
accountNumber = [Link];
accountHolderName = [Link];
balance = [Link];
}
void checkBalance() {
[Link]("Account Number: " + accountNumber);
[Link]("Account Holder: " + accountHolderName);
[Link]("Balance: " + balance);
}
}
class Main {
public static void main(String[] args) {
// Base Class
class Animal {
void walk() {
[Link]("I am walking");
}
}
void sing() {
[Link]("I am singing");
}
}
class Main {
public static void main(String[] args) {
Bird b = new Bird();
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) {
int num = 5;
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]());
} 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) {
try {
[Link]("Enter value of a: ");
int a = [Link]();
int result = a / b;
} 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]().
String threadName;
MyThread(String name) {
threadName = name;
}
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
MyThread(String name) {
super(name); // set thread name
}
public void run() {
[Link]("Running: " + getName() +
" | Priority: " + getPriority());
}
}
class Main {
public static void main(String[] args) {
[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]");
int ch;
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;
import [Link];
import [Link];
class StreamExample {
[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) {
import [Link];
import [Link];
class QueueExample {
public static void main(String[] args) {
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
import [Link];
import [Link];
class SetExample {
public static void main(String[] args) {
[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) {
[Link]("Amit", 85);
[Link]("Yash", 90);
[Link]("Abhinav", 75);
[Link]("Swastika", 95);
[Link]("Ashutosh", 80);
[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].*;
[Link](list);
[Link]("Sorted by ID:");
for (Student s : list) {
[Link](s);
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Repository
class UserRepository {
@Autowired
private UserRepository userRepository;
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]);
PrototypeBean p1 = [Link]([Link]);
PrototypeBean p2 = [Link]([Link]);
[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() {}