0% found this document useful (0 votes)
6 views57 pages

Java File

The document outlines a series of Java programming experiments, covering topics such as using the Java compiler, OOP concepts, inheritance, polymorphism, exception handling, multi-threading, and file I/O operations. Each experiment includes objectives, sample code, and expected outputs. The experiments aim to provide practical experience in Java programming and application development using various frameworks and techniques.

Uploaded by

Ashutosh Shukla
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)
6 views57 pages

Java File

The document outlines a series of Java programming experiments, covering topics such as using the Java compiler, OOP concepts, inheritance, polymorphism, exception handling, multi-threading, and file I/O operations. Each experiment includes objectives, sample code, and expected outputs. The experiments aim to provide practical experience in Java programming and application development using various frameworks and techniques.

Uploaded by

Ashutosh Shukla
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
You are on page 1/ 57

INDEX

S Object Date Page Sign


No. No.
1. Use Java compiler and Eclipse platform to 2-4
write and execute Java program.

2. Create simple Java program using 5-6


Command Line argument.

3. Understand OOP concepts and basics of 7 - 10


Java programming.

4. Create Java programs using inheritance 11 - 14


and polymorphism.
5. Implement error-handling techniques 15 – 20
using exception handling and multi
threading.
6. Create Java program with the use of Java 21 – 25
packages.

7. Construct Java program using Java I/O 26 – 29


packages.
8. Create industry oriented application 30 - 47
using Spring Framework.

9. Test RESTful web service using Spring 48 - 52


Boot.
10. Test frontend web application with Spring 53 - 57
Boot.

1|Page
Experiment 01

Objective:- Use Java compiler and Eclipse platform to write


and execute Java program.

PROGRAM

import java.util.Scanner;

import java.util.Scanner; // Import Scanner class

public class HelloWorld { // Driver Class

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: "); // Taking user inputs


String name = scanner.nextLine();

System.out.print("Enter your department: ");


String department = scanner.nextLine();

System.out.print("Enter your year of study: ");


int year = scanner.nextInt();
scanner.nextLine();

2|Page
System.out.print("Enter your section: ");
String section = scanner.nextLine();

System.out.print("Enter your roll number: ");


int rollNo = scanner.nextInt();

System.out.println("\n******** User Details ********");


System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Year of Study: " + year);
System.out.println("Section: " + section);
System.out.println("Roll Number: " + rollNo);

scanner.close();
}
}

3|Page
OUTPUT

4|Page
Experiment 02

Objective:- Create simple Java program using Command


Line argument.

PROGRAM

public class CammandLineArgs { // Driver class

public static void main(String[ ] args) {

if (args.length > 0) { // Check if arguments are provided


System.out.println("Command Line Arguments:");
for (String arg : args) {
System.out.println(arg);
}
}
else {
System.out.println("No command line arguments provided.");
}
}

5|Page
OUTPUT

6|Page
Experiment 03
Objective:- Understand OOP concepts and basics of Java
programming.

PROGRAM

import java.util.Scanner;

class BankAccount { // Encapsulation


private double balance;
public BankAccount(double initialBalance) { // Constructor to initialize
account balance
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: Rs." + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: Rs." + amount);
} else {
System.out.println("Insufficient balance or invalid amount.");
}
}

7|Page
public double getBalance() {
return balance;
}
}

class SavingsAccount extends BankAccount { // Inheritance


private double interestRate;
public SavingsAccount(double initialBalance, double interestRate) {
super(initialBalance); // Calling the constructor of the parent class
this.interestRate = interestRate;
}
public void addInterest() {
double interest = getBalance() * (interestRate / 100);
deposit(interest);
System.out.println("Interest added: Rs." + interest);
}
}

public class BankingSystem { // Driver class


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
SavingsAccount account = new SavingsAccount(1000, 5);

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");
}
}

public class VehicleManager { // Main Class


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter vehicle type (Car/Bike/Truck): ");
String type = scanner.nextLine().trim();

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();

Vehicle vehicle = null;

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;
}

System.out.println("\n=== Vehicle Info ===");


vehicle.displayInfo();

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;

class InvalidNumberException extends Exception { // Exception Class


public InvalidNumberException(String message) {
super(message);
}
}
public class ExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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
}

System.out.println("Result: " + (num1 / num2));


System.out.println("Enter an index (0-" + (size - 1) + ") to access
entered array elements:");
int index = scanner.nextInt();
System.out.println("Value: " + numbers[index]);
System.out.println("Enter a positive number:");
int userInput = scanner.nextInt();
if (userInput < 0) {
throw new InvalidNumberException("Negative numbers are not
allowed!");
}

System.out.println("Valid number entered: " + userInput);

} 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;

class WorkerThread extends Thread {


private final int workerId;

public WorkerThread(int workerId) {


this.workerId = workerId;
}

@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.");
}
}

public class MultiThread {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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

System.out.println("Starting " + numberOfWorkers + " worker


threads...");

for (int i = 1; i <= numberOfWorkers; i++) {


WorkerThread worker = new WorkerThread(i);
worker.start();
}

System.out.println("All worker threads initiated.");


}
}

19 | P a g e
OUTPUT

20 | P a g e
Experiment 06
Objective:- Create Java program with the use of Java packages.

Folder Directory Structure

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;
}

public int sub(int num1, int num2) {


return num1 - num2;
}

public int multiply(int num1, int num2) {


return num1 * num2;
}

public double divide(int num1, int num2) {


if (num2 == 0) {
throw new ArithmeticException("Cannot divide by Zero");
}
return (double) num1 / num2;
}
public void closeScanner() {
scanner.close();
}
}

22 | P a g e
b) MainApp.java

PROGRAM

package CalculatorApp ;

import CalculatorApp.Calculator; // Importing Calculator class


import java.util.Scanner; // Import Scanner for user input

public class MainApp { // Driver class


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator obj = new Calculator(); // Creating object of class
calculator
while (true) {
System.out.println("\n--- Calculator Menu ---");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Choose an operation: ");
int choice = scanner.nextInt();

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

Objective:- Construct Java program using Java I/O packages.

Folder Directory Structure

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

Objective:- Create industry oriented application using Spring


Framework.
Folder Directory Structure

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;

public Patient(String id, String name, String contact) {


this.id = id;
this.name = name;
this.contact = contact;
}

public String getId() { return id; } // Getters


public String getName() { return name; }
public String getContact() { return 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;

public Doctor(String id, String name, String specialization) {


this.id = id;
this.name = name;
this.specialization = specialization;
}
public String getId() { return id; } // Getters
public String getName() { return name; }
public String getSpecialization() { return 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;

public class PatientService {


private static final String FILENAME = "src\\database\\patients.txt";
public void addPatient(Patient patient) throws IOException {
List<String> patients = FileUtil.readFromFile(FILENAME);
patients.add(patient.toString());
FileUtil.writeToFile(FILENAME, patients);
}
public List<Patient> getAllPatients() throws IOException {
List<String> data = FileUtil.readFromFile(FILENAME);

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;

public class DoctorService {


private static final String FILENAME = "src\\database\\doctors.txt";

public void addDoctor(Doctor doctor) throws IOException {


List<String> doctors = FileUtil.readFromFile(FILENAME);
doctors.add(doctor.toString());
FileUtil.writeToFile(FILENAME, doctors);
}

public List<Doctor> getAllDoctors() throws IOException {


List<String> data = FileUtil.readFromFile(FILENAME);
List<Doctor> doctors = new ArrayList<>();
for (String line : data) {
doctors.add(Doctor.fromString(line));
}
return doctors;
}

public Doctor findDoctorById(String id) throws IOException {


List<Doctor> doctors = getAllDoctors();
for (Doctor doctor : doctors) {
if (doctor.getId().equals(id)) {
return doctor;
}
}
return null;
}
}

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;

public class FileUtil {


public static void writeToFile(String filename, List<String> data) throws
IOException {
try (FileWriter writer = new FileWriter(filename)) {
for (String line : data) {
writer.write(line + "\n");
}
}
}
public static List<String> readFromFile(String filename) throws IOException {

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;

public class Main {


private static Scanner scanner = new Scanner(System.in);
private static PatientService patientService = new PatientService();
private static DoctorService doctorService = new DoctorService();
private static AppointmentService appointmentService = new
AppointmentService();
public static void main(String[] args) {
boolean running = true;
while (running) {
System.out.println("\n=== Hospital Management System ===");

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: ");

int choice = scanner.nextInt();


scanner.nextLine();
switch (choice) {
case 1:
System.out.print("Enter Patient ID: ");
String id = scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Contact: ");
String contact = scanner.nextLine();
patientService.addPatient(new Patient(id, name, contact));
System.out.println("Patient added successfully!");
break;
case 2:
System.out.println("\n=== Patient List ===");
for (Patient patient : patientService.getAllPatients()) {
System.out.println("ID: " + patient.getId() +
", Name: " + patient.getName() +
", Contact: " + patient.getContact());
}
break;
case 3:
System.out.print("Enter Patient ID: ");

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;
}

appointmentService.addAppointment(new Appointment(id, patientId,


doctorId, date));
System.out.println("Appointment added successfully!");
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.

Folder Directory Structure

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;

public class Student {


private int id;
private String name;
private String department;
public Student() {}

public Student(int id, String name, String department) {


this.id = id;
this.name = name;
this.department = department;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department;
}
}

49 | P a g e
c) StudentController.java

PROGRAM

package com.example.studentdemo.model;

public class Student {


private int id;
private String name;
private String department;
public Student() {}

public Student(int id, String name, String department) {


this.id = id;
this.name = name;
this.department = department;
}

public int getId() { return id; }


public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department;
}
}

50 | P a g e
TESTING THE API

1. GET All Students


GET http://localhost:8080/api/students
Output:
[
{"id": 1, "name": "Anurag", "department": "Computer Science"},
{"id": 2, "name": "Kartik", "department": "Electrical Engineering"},
{"id": 3, "name": "Amit", "department": "Mechanical Engineering"}
]

2. GET Student by ID (2)


GET http://localhost:8080/api/students/2
Output:
{"id": 2, "name": "Kartik", "department": "Electrical Engineering"}

3. POST New Student


POST http://localhost:8080/api/students
Body: {"id": 4, "name": "Sumit", "department": "Civil Engineering"}
Output:
{"id": 4, "name": "Sumit", "department": "Civil Engineering"}

4. PUT Update Student (3)


PUT http://localhost:8080/api/students/3
Body: {"id": 3, "name": "Sunny", "department": "Aerospace Engineering"}
Output:
{"id": 3, "name": "Sunny", "department": "Aerospace Engineering"}

5. DELETE Student (2)


DELETE http://localhost:8080/api/students/2
Output:
Student with ID 2 deleted

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

Objective:- Test frontend web application with Spring Boot.


Folder Directory Structure

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

<project xmlns="http://maven.apache.org/POM/4.0.0" ...>

<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

1. Go to the project root folder:


mvn spring-boot:run

2. Open browser at http://localhost:8080/

3. When the page loads:


Greeting App
[ Input box ] [Greet button]
If you enter Anurag and click Greet, the page shows:
Hello, Anurag!

4. Image:

57 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy