Java File
Java File
1|Page
Experiment 01
PROGRAM
import java.util.Scanner;
2|Page
System.out.print("Enter your section: ");
String section = scanner.nextLine();
scanner.close();
}
}
3|Page
OUTPUT
4|Page
Experiment 02
PROGRAM
5|Page
OUTPUT
6|Page
Experiment 03
Objective:- Understand OOP concepts and basics of Java
programming.
PROGRAM
import java.util.Scanner;
7|Page
public double getBalance() {
return balance;
}
}
while (true) {
System.out.println("\n--- Banking System ---");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Add Interest");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
switch (choice) {
8|Page
case 1:
System.out.print("Enter deposit amount: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter withdrawal amount: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
System.out.println("Current Balance: Rs." + account.getBal
ance());
break;
case 4:
account.addInterest();
break;
case 5:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
9|Page
OUTPUT
10 | P a g e
Experiment 04
Objective:- Create Java programs using inheritance and
polymorphism.
PROGRAM
import java.util.Scanner;
class Vehicle { // Base class
protected String brand;
protected int speed;
public Vehicle(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
public void displayInfo() {
System.out.println("Vehicle Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
class Car extends Vehicle { // Derived class: Car
private int doors;
public Car(String brand, int speed, int doors) {
super(brand, speed);
this.doors = doors;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Car Doors: " + doors);
System.out.println("Type: Car");
11 | P a g e
}
}
class Bike extends Vehicle { // Derived class: Bike
private boolean hasGear;
public Bike(String brand, int speed, boolean hasGear) {
super(brand, speed);
this.hasGear = hasGear;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Has Gear: " + (hasGear ? "Yes" : "No"));
System.out.println("Type: Bike");
}
}
class Truck extends Vehicle { // Derived class: Truck
private int capacity;
public Truck(String brand, int speed, int capacity) {
super(brand, speed);
this.capacity = capacity;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Cargo Capacity: " + capacity + " tons");
System.out.println("Type: Truck");
}
}
12 | P a g e
System.out.print("Enter brand name: ");
String brand = scanner.nextLine();
System.out.print("Enter speed (km/h): ");
int speed = scanner.nextInt();
switch (type.toLowerCase()) {
case "car":
System.out.print("Enter number of doors: ");
int doors = scanner.nextInt();
vehicle = new Car(brand, speed, doors);
break;
case "bike":
System.out.print("Does it have gear? (true/false): ");
boolean hasGear = scanner.nextBoolean();
vehicle = new Bike(brand, speed, hasGear);
break;
case "truck":
System.out.print("Enter cargo capacity (tons): ");
int capacity = scanner.nextInt();
vehicle = new Truck(brand, speed, capacity);
break;
default:
System.out.print("Invalid vehicle type!");
break;
}
scanner.close();
}
}
13 | P a g e
OUTPUT
14 | P a g e
Experiment 05
Objective:- Implement error-handling techniques using
exception handling and multi threading.
a) Exception Handling
PROGRAM
import java.util.Scanner;
try {
System.out.print("Enter the number of elements in the array:");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " array elements:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println("Enter two numbers for division:");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero!");
15 | P a g e
}
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid array index!");
} catch (InvalidNumberException e) {
System.out.println("Custom Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Unknown Error Occurred: " + e.getMessage());
} finally {
System.out.println("Program execution complete.");
scanner.close();
}
}
16 | P a g e
OUTPUT
17 | P a g e
b) Multi Threading
PROGRAM
import java.util.Scanner;
@Override
public void run() {
System.out.println("Worker " + workerId + " started.");
try {
Thread.sleep((int) (Math.random() * 1000)); // Simulating task
processing
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Worker " + workerId + " finished task.");
}
}
18 | P a g e
System.out.print("Enter the number of worker threads: ");
int numberOfWorkers = scanner.nextInt();
scanner.close(); // Close the scanner after input
19 | P a g e
OUTPUT
20 | P a g e
Experiment 06
Objective:- Create Java program with the use of Java packages.
CalculatorApp/
│ |── src/
│ |── Claculator.java # Package for the main program
│── MainApp.java # Package for utility classes
a) Claculator.java
PROGRAM
package Calculator.src;
import java.util.Scanner; // Import scanner for user input
public class Calculator {
private Scanner scanner;
public Calculator() { // Constructor to initialize Scanner
scanner = new Scanner(System.in);
}
public int getUserInput(String message) { // Method to take input from user
System.out.print(message);
return scanner.nextInt();
}
21 | P a g e
public int add(int num1, int num2) {
return num1 + num2;
}
22 | P a g e
b) MainApp.java
PROGRAM
package CalculatorApp ;
if (choice == 5) {
System.out.println("Exiting...");
scanner.close();
obj.closeScanner();
return;
}
int num1 = obj.getUserInput("Enter first number: "); // Get user input for
number
23 | P a g e
int num2 = obj.getUserInput("Enter second number: ");
switch (choice) {
case 1:
System.out.println("Sum: " + obj.add(num1, num2));
break;
case 2:
System.out.println("Subtraction: " + obj.sub(num1, num2));
break;
case 3:
System.out.println("Multiplication: " + obj.multiply(num1,
num2));
break;
case 4:
try {
System.out.println("Quotient: " + obj.divide(num1, num2));
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
24 | P a g e
OUTPUT
25 | P a g e
Experiment 07
FileIOApp/
│ |── src/
│ |── FileHandler.java # Package for file operations
│── FileIOApp.java # Package for main application
|── data.txt #After executing the program it is automatically created
a) FileHandler.java
PROGRAM
package FileIOApp.src;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileHandler {
private final String filename = "data.txt"; // File to store data
public void writeToFile(String text) { // Method to write user input
try (FileWriter writer = new FileWriter(filename, true)) { // Append mode
writer.write(text + "\n");
System.out.println("Data saved successfully!");
26 | P a g e
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
public void readFromFile() { // Method to read data from file
try (FileReader reader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(reader)) {
System.out.println("\n--- File Content ---");
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
}
}
b) FileIOApp.java
PROGRAM
package FileIOApp;
import FileIOApp.src.FileHandler; // Importing FileHandler class
import java.util.Scanner;
public class FileIOApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
FileHandler fileHandler = new FileHandler()
27 | P a g e
while (true) {
System.out.println("\n--- File I/O Menu ---");
System.out.println("1. Write to File");
System.out.println("2. Read from File");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter text to save: ");
String text = scanner.nextLine();
fileHandler.writeToFile(text);
break;
case 2:
fileHandler.readFromFile();
break;
case 3:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Try again.");
}
}
}
}
28 | P a g e
OUTPUT
29 | P a g e
Experiment 08
hospital-management/
│
│ ── src/
│ │
│ │ ── model/ # Data models
│ │ │ ── Patient.java
│ │ │ ── Doctor.java
│ │ └── Appointment.java
│ │ ── service/ # Business
│ │ │ ── PatientService.java
│ │ │ ── DoctorService.java
│ │ └── AppointmentService.java
│ │ ── util/ # Utilities
│ │ └── FileUtil.java
│ └── Main.java
│ # Entry point Main Application
│── database/ # Data storage
│── patients.txt
│── doctors.txt
│── appointments.txt
30 | P a g e
a) Patient.java(model)
PROGRAM
package model;
public class Patient {
private String id;
private String name;
private String contact;
@Override
public String toString() {
return id + "," + name + "," + contact;
}
public static Patient fromString(String data) {
String[] parts = data.split(",");
return new Patient(parts[0], parts[1], parts[2]);
}
}
31 | P a g e
b) Doctor.java(model)
PROGRAM
package model;
public class Doctor {
private String id;
private String name;
private String specialization;
@Override
public String toString() {
return id + "," + name + "," + specialization;
}
public static Doctor fromString(String data) {
String[] parts = data.split(",");
return new Doctor(parts[0], parts[1], parts[2]);
}
32 | P a g e
c) Appointment.java(model)
PROGRAM
package model;
public class Appointment {
private String id;
private String patientId;
private String doctorId;
private String date;
public Appointment(String id, String patientId, String doctorId, String date) {
this.id = id;
this.patientId = patientId;
this.doctorId = doctorId;
this.date = date;
}
public String getId() { return id; } // Getters
public String getPatientId() { return patientId; }
public String getDoctorId() { return doctorId; }
public String getDate() { return date; }
@Override
public String toString() {
return id + "," + patientId + "," + doctorId + "," + date;
}
public static Appointment fromString(String data) {
33 | P a g e
String[] parts = data.split(",");
return new Appointment(parts[0], parts[1], parts[2], parts[3]);
}
}
d) PatientService.java(service)
PROGRAM
package service;
import model.Patient;
import util.FileUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
34 | P a g e
List<Patient> patients = new ArrayList<>();
for (String line : data) {
patients.add(Patient.fromString(line));
}
return patients;
}
public Patient findPatientById(String id) throws IOException {
List<Patient> patients = getAllPatients();
for (Patient patient : patients) {
if (patient.getId().equals(id)) {
return patient;
}
}
return null;
}
}
e) DoctorService.java(service)
PROGRAM
package service;
import model.Doctor;
import util.FileUtil;
import java.io.IOException;
35 | P a g e
import java.util.ArrayList;
import java.util.List;
36 | P a g e
f) AppointmentService.java(service)
PROGRAM
package service;
import model.Appointment;
import util.FileUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class AppointmentService {
private static final String FILENAME = "src\\database\\appointments.txt";
public void addAppointment(Appointment appointment) throws IOException {
List<String> appointments = FileUtil.readFromFile(FILENAME);
appointments.add(appointment.toString());
FileUtil.writeToFile(FILENAME, appointments);
}
public List<Appointment> getAllAppointments() throws IOException {
List<String> data = FileUtil.readFromFile(FILENAME);
List<Appointment> appointments = new ArrayList<>();
for (String line : data) {
appointments.add(Appointment.fromString(line));
}
return appointments;
}
37 | P a g e
public Appointment findAppointmentById(String id) throws IOException {
List<Appointment> appointments = getAllAppointments();
for (Appointment appointment : appointments) {
if (appointment.getId().equals(id)) {
return appointment;
}
}
return null;
}
}
g) FileUtil.java (util)
PROGRAM
package util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
38 | P a g e
List<String> data = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filename)))
{
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty()) {
data.add(line);
}
}
}
return data;
}
}
h) Main.java
PROGRAM
import model.*;
import service.*;
import java.io.IOException;
import java.util.Scanner;
39 | P a g e
System.out.println("1. Patient Management");
System.out.println("2. Doctor Management");
System.out.println("3. Appointment Management");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine();
try {
switch (choice) {
case 1:
patientManagement();
break;
case 2:
doctorManagement();
break;
case 3:
appointmentManagement();
break;
case 4:
running = false;
System.out.println("Exiting system.");
System.out.println("Thank You for using Hospital Management System.
Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
40 | P a g e
private static void patientManagement() throws IOException {
boolean back = false;
while (!back) {
System.out.println("\n=== Patient Management ===");
System.out.println("1. Add Patient");
System.out.println("2. View Patients");
System.out.println("3. Search Patient");
System.out.println("4. Back to Main Menu");
System.out.print("Enter your choice: ");
41 | P a g e
Patient patient = patientService.findPatientById(scanner.nextLine());
if (patient != null) {
System.out.println("Patient found:");
System.out.println("ID: " + patient.getId() +
", Name: " + patient.getName() +
", Contact: " + patient.getContact());
} else {
System.out.println("Patient not found.");
}
break;
case 4:
back = true;
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
private static void doctorManagement() throws IOException {
boolean back = false;
while (!back) {
System.out.println("\n=== Doctor Management ===");
System.out.println("1. Add Doctor");
System.out.println("2. View Doctors");
System.out.println("3. Search Doctor");
System.out.println("4. Back to Main Menu");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.print("Enter Doctor ID: ");
String id = scanner.nextLine();
System.out.print("Enter Name: ");
42 | P a g e
String name = scanner.nextLine();
System.out.print("Enter Specialization: ");
String specialization = scanner.nextLine();
doctorService.addDoctor(new Doctor(id, name, specialization));
System.out.println("Doctor added successfully!");
break;
case 2:
System.out.println("\n=== Doctor List ===");
for (Doctor doctor : doctorService.getAllDoctors()) {
System.out.println("ID: " + doctor.getId() +
", Name: " + doctor.getName() +
", Specialization: " + doctor.getSpecialization());
}
break;
case 3:
System.out.print("Enter Doctor ID: ");
Doctor doctor = doctorService.findDoctorById(scanner.nextLine());
if (doctor != null) {
System.out.println("Doctor found:");
System.out.println("ID: " + doctor.getId() +
", Name: " + doctor.getName() +
", Specialization: " + doctor.getSpecialization());
} else {
System.out.println("Doctor not found.");
}
break;
case 4:
back = true;
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
43 | P a g e
private static void appointmentManagement() throws IOException {
boolean back = false;
while (!back) {
System.out.println("\n=== Appointment Management ===");
System.out.println("1. Add Appointment");
System.out.println("2. View Appointments");
System.out.println("3. Search Appointment");
System.out.println("4. Back to Main Menu");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.print("Enter Appointment ID: ");
String id = scanner.nextLine();
System.out.print("Enter Patient ID: ");
String patientId = scanner.nextLine();
System.out.print("Enter Doctor ID: ");
String doctorId = scanner.nextLine();
System.out.print("Enter Date: ");
String date = scanner.nextLine();
if (patientService.findPatientById(patientId) == null) {
System.out.println("Patient not found.");
break;
}
if (doctorService.findDoctorById(doctorId) == null) {
System.out.println("Doctor not found.");
break;
}
44 | P a g e
case 2:
System.out.println("\n=== Appointment List ===");
for (Appointment appt : appointmentService.getAllAppointments()) {
System.out.println("ID: " + appt.getId() +
", Patient ID: " + appt.getPatientId() +
", Doctor ID: " + appt.getDoctorId() +
", Date: " + appt.getDate());
}
break;
case 3:
System.out.print("Enter Appointment ID: ");
Appointment appt =
appointmentService.findAppointmentById(scanner.nextLine());
if (appt != null) {
System.out.println("Appointment found:");
System.out.println("ID: " + appt.getId() +
", Patient ID: " + appt.getPatientId() +
", Doctor ID: " + appt.getDoctorId() +
", Date: " + appt.getDate());
} else {
System.out.println("Appointment not found.");
}
break;
case 4:
back = true;
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
45 | P a g e
OUTPUT
46 | P a g e
Database
a) doctors.txt
b) patients.txt
c) appointments.txt
47 | P a g e
Experiment 09
Objective:- Test RESTful web service using Spring Boot.
student-service/
│── src/
│ └──main/
│ └── java/
│ └── com/
│ └──example/
│ └── studentdemo/
│ │ └── StudentApplication.java #Main Spring Boot
│ │ application
│ │─ controller/
│ │ └── StudentController.java # REST controller
│ │ ── model/
│ └── Student.java # Student entity/model
│── target/ # Generated build files
│── pom.xml # Maven build file
a) StudentApplication.java
PROGRAM
package com.example.studentdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
48 | P a g e
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
b) Student.java
PROGRAM
package com.example.studentdemo.model;
49 | P a g e
c) StudentController.java
PROGRAM
package com.example.studentdemo.model;
50 | P a g e
TESTING THE API
51 | P a g e
Final State After All Operations:
GET http://localhost:8080/api/students
Output:
[
{"id": 1, "name": "Anurag", "department": "Computer Science"},
{"id": 3, "name": "Sunny", "department": "Aerospace Engineering"},
{"id": 4, "name": "Sumit", "department": "Civil Engineering"}
]
52 | P a g e
Experiment 10
spring-frontend-demo/
│ ── src/
│ └── main/
│ │ ── java/
│ │ └── com/
│ │ └── example/
│ │ └── demo/
│ │ │ ── DemoApplication.java
│ │ └── GreetingController.java
│ └── resources/
│ │ ── static/
│ │ └── index.html
│ └── application.properties
└── pom.xml
a) pom.xml
PROGRAM
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
53 | P a g e
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-frontend-demo</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
54 | P a g e
b) DemoApplication.java
PROGRAM
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
c) GreetingController.java
PROGRAM
package com.example.demo;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin
public class GreetingController {
@GetMapping("/api/greet")
public String greet(@RequestParam(defaultValue = "World") String name) {
return "Hello, " + name + "!";
55 | P a g e
}
}
d) index.html
PROGRAM
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spring Boot Web Test</title>
</head>
<body>
<h1>Greeting App</h1>
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="fetchGreeting()">Greet</button>
<p id="greetingResult"></p>
<script>
function fetchGreeting() {
const name = document.getElementById("nameInput").value;
fetch(`/api/greet?name=${encodeURIComponent(name)}`)
.then(response => response.text())
.then(data => {
document.getElementById("greetingResult").textContent = data;
});
}
</script>
</body>
</html>
56 | P a g e
OUTPUT
4. Image:
57 | P a g e