PBLJ Lab Manual PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Experiment -1.

Create an application to save the employee information using arrays having following fields:
empid[],depName[],empDes,empName[],dateJoin[],basic[],hra[],it[], Des
Codes

Tasks:
(a) Salary should be calculated as (Basic+HRA+DA IT)
(b) Printing designation and da according to employee designation.

1. Aim/Overview of the practical:


The Aim of the practical is to store the data of employees’ information using array.

2. Task to be done:
We need to declare multiple arrays of required data types and insert values in them. The index
is using to collect each information from each array and group together to find the total
information of a certain employee.

3. Code
package com.Program2;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n;
Scanner sk = new Scanner(System.in);
System.out.print("Enter the number of entries: ");
n = sk.nextInt(); // Taking input of the number of entries
// Declaring array with suitable data type and size of n
String empID[] = new String[n];
String depName[] = new String[n];
String empName[] = new String[n];
String dateJoin[] = new String[n];
int basic[] = new int[n];
int hra[] = new int[n];
int it[] = new int[n];
char DesCode[] = new char[n];
String empID_search;
//Statically initialising the Designation codes, Designation, DA
char DesCode_fixed[] = {'e', 'c', 'k', 'r', 'm'};
String designation[] = {"Engineer", "Consultant", "Clerk", "Receptionist", "Manager"};
int DA[] = {20000, 32000, 12000, 15000, 40000};
System.out.println("Enter the details\n");
//Taking input of each Employee
for(int i = 0; i < n; i++)

1|Page
{
System.out.print("Employee " + (i+1) + "\n");
System.out.print("ID: ");
empID[i] = sk.next();
sk.nextLine();
System.out.print("Department Name: ");
depName[i] = sk.next();
sk.nextLine();
System.out.print("Name: ");
empName[i] = sk.next();
sk.nextLine();
System.out.print("Date of Join: ");
dateJoin[i] = sk.next();
sk.nextLine();
System.out.print("Basic: ");
basic[i] = sk.nextInt();
System.out.print("HRA: ");
hra[i] = sk.nextInt();
System.out.print("IT: ");
it[i] = sk.nextInt();
System.out.print("Designation Code: ");
DesCode[i] = sk.next().charAt(0);
sk.nextLine();
System.out.println();
}
System.out.print("Enter the Employee ID to search: ");
empID_search = sk.next();
int idx = -1;
//Finding the index of inputted employee ID
for(int i = 0; i < n; i++)
{
if(empID_search.equals(empID[i]))
{
idx = i;
break;
}
}
// If the employee ID not present, then the program ends here
if(idx == -1)
{
System.out.println("The Employee ID you requested is not available");
}
else
{
int resultant_salaray = 0;
char desCode;

2|Page
desCode = DesCode[idx];
int idx2 = 0;
//Finding Designation and DA based on the Designation Code
for(int i = 0; i < 5; i++)
{
if(desCode == DesCode_fixed[i])
{
idx2 = i;
break;
}
}
//Calculation the Salary
resultant_salaray = basic[idx] + hra[idx] + DA[idx2] - it[idx];
System.out.println("Emp No. Emp Name Department Designation Salary");
System.out.printf("%s%17s%18s%15s%15s",empID[idx],empName[idx], depName[idx],
designation[idx2] , resultant_salaray);
}
}
}

4. Output:

3|Page
4|Page
Experiment -1.2

Design and implement a simple inventory control system for a small video rental store.

1. Aim/Overview of the practical:


To understand the concepts of classes, inheritance and other concepts of Java language for
the development of Projects.

2. Task to be done:
Design and implement a simple inventory control system for a small video rental store

3. Code:

VIDEO CLASS CODE:


package com.Program2;
public class Video
{
String videoName;
boolean avail_for_checkout = true;
int number_of_rating = 0;
int rating = 0;
public Video(String input)
{
videoName = input;
}
public Video()
{
}
public String getName()
{
return videoName;
}
public void doCheckOut()
{
System.out.println("The movie " + videoName + " is Checked out!!");
avail_for_checkout = false;
}
public void doReturn()
{
System.out.println("The movie " + videoName + " is Returned!!");
avail_for_checkout = true;
}
public void receiveRating(int input)
{
number_of_rating++;
rating = rating + input;
}
public int getRating()

5|Page
{
if(number_of_rating == 0)
{
return 0;
}
return rating/number_of_rating;
}
public boolean is_avail_for_Checkout()
{
return avail_for_checkout;
}
}

VIDEOSTORE CLASS CODE:


package com.Program2;
public class VideoStore extends Video
{
Video store[];
static int i = 0;
public VideoStore(int input)
{
super();
store = new Video[input];
}
public void addVideo(String name)
{
store[i] = new Video(name);
System.out.println("The movie " + name + " is Added.");
i++;
}
public int movie_finder(String name)
{
for(int j = 0; j < i; j++)
{
if(store[j].getName().equals(name))
{
return j;
}
}
return -1;
}
public void doCheckout(String name)
{
int idx = movie_finder(name);
if(idx != -1)
{
if(store[idx].is_avail_for_Checkout())
{

6|Page
store[idx].doCheckOut();
}
else
{
System.out.println("The movie \"" + "\" is not available for Checkout");
}
}
else
{
System.out.println("The Movie Title you gave is not present in the list inventory. Please
check the Spelling");
}
}
public void doReturn(String name)
{
int idx = movie_finder(name);
if(idx == -1)
{
System.out.println("The movie you want to return is not present in the List Inventory. Please
check the Spelling");
}
else
{
store[idx].doReturn();
}
}
public boolean movieStatus(String name)
{
int idx = movie_finder(name);
return store[idx].is_avail_for_Checkout();
}
public void receiveRating(String name, int rating)
{
int idx = movie_finder(name);
if(idx != -1)
{
store[idx].receiveRating(rating);
System.out.println("You rated the movie " + name + " '" + rating + "'");
}
else
{
System.out.println("The Movie Title you gave is not present in the list inventory. Please
check the Spelling");
}
}
public void listInventory()
{
System.out.printf("S.No Title Average_Rating Availability\n");

7|Page
for(int k = 0; k < i; k++)
{
if(store[k].is_avail_for_Checkout())
{
System.out.printf("%d%16s%10d%25s\n", k+1, store[k].getName(), store[k].getRating(),
"True" );
}
else
{
System.out.printf("%d%16s%10d%25s\n", k+1, store[k].getName(), store[k].getRating(),
"False" );
}
}
}
}

MAIN CLASS CODE:


package com.Program2;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static void main(String args[]) throws IOException, InterruptedException
{
int ch1, ch2;
boolean stat1 = true;
String passwordforadmin = "Password";
VideoStore object = new VideoStore(10);
Scanner sk = new Scanner(System.in);
while(stat1)
{
System.out.println("\nPress 1: To Login as a User");
System.out.println("Press 2: To Login as Admin");
System.out.println("Press 3: To Terminate");
System.out.print("Input- ");
ch1 = sk.nextInt();
String check;
switch(ch1)
{
case 1:
boolean stat2 = true;
while(stat2)
{
System.out.println("\nPress 1: To check if the Movie present");
System.out.println("Press 2: To Check out a Movie");
System.out.println("Press 3: To Return a Movie");
System.out.println("Press 4: To Give Rating to a Movie");
System.out.println("Press 5: To display the List Inventory");

8|Page
System.out.println("Press 6: To Log out");
System.out.println("Press 7: To Terminate");
System.out.print("Input: ");
ch2 = sk.nextInt();
String name;
switch (ch2) {
case 1:
System.out.print("\nEnter the Title of the Movie: ");
sk.nextLine();
name = sk.nextLine();
System.out.println("The Status of the Movie is " + object.movieStatus(name));
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat2 = false;
stat1 = false;
}
break;
case 2:
System.out.print("\nEnter the Title of the movie to Checkout: ");
sk.nextLine();
name = sk.nextLine();
object.doCheckout(name);
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat2 = false;
stat1 = false;
}
break;
case 3:
System.out.print("\nEnter the Title of the movie to Return: ");
sk.nextLine();
name = sk.nextLine();
object.doReturn(name);
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat2 = false;
stat1 = false;
}
break;
case 4:
System.out.print("\nEnter the Title of the movie that you want to give rating: ");
sk.nextLine();
name = sk.nextLine();
System.out.print("Enter the Rating: ");
int rating = sk.nextInt();

9|Page
object.receiveRating(name, rating);
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat2 = false;
stat1 = false;
}
break;
case 5:
object.listInventory();
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat2 = false;
stat1 = false;
}
break;
case 6:
stat2 = false;
break;
case 7:
stat1 = false;
stat2 = false;
break;
}
}
break;
case 2:
String input_password;
boolean stat3 = true;
while (stat3)
{
System.out.print("Enter the Password: ");
input_password = sk.next();
if (!input_password.equals(passwordforadmin))
{
System.out.println("You have entered Incorrect Password. Try Again!!");
System.out.println("Press Enter to continue...");
try
{
System.in.read();
}
catch(Exception e) {}
}
else
{
stat3 = false;
}

10 | P a g e
}
boolean stat4 = true;
while(stat4)
{
System.out.println("\nPress 1: To Add a Movie");
System.out.println("Press 2: To Display Inventory List");
System.out.println("Press 3: To Logout");
System.out.println("Press 4: To Terminate");
int ch3 = sk.nextInt();
switch (ch3)
{
case 1:
String title;
System.out.print("Enter the Title of the Movie: ");
sk.nextLine();
title = sk.nextLine();
object.addVideo(title);
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat4 = false;
stat1 = false;
}
break;
case 2:
object.listInventory();
System.out.print("Do you want to Exit or visit the Main Menu Again? ");
check = sk.next();
if(check.equals("Exit") || check.equals("exit") || check.equals("E") || check.equals("e")) {
stat4 = false;
stat1 = false;
}
break;
case 3:
stat4 = false;
break;
case 4:
stat4 = false;
stat1 = false;
break;
}
}
break;
case 3:
stat1 = false;
break;
}
}

11 | P a g e
}
}

4. Output:

12 | P a g e
13 | P a g e
14 | P a g e
15 | P a g e
Experiment 1.3

Create an application to calculate interest for FDs, RDs based on certain conditions using
inheritance.

1. Aim/Overview of the practical:


Create an application to calculate interest for FDs, RDs based on certain conditions using
inheritance.

2. Task to be done:
We need to create an Abstract class (Account) and extend this class using FDAccount,
RDAcount and SBAccount class respectively. We need to implement, calculateInterest()
abstract function in the sub classes to calculate Interest respectively based on Principle
Amount, age, Maturity Period, etc.

3. Code:
ACCOUNT CLASS:
package com.Exp3;
abstract class Account
{
protected double interestRate;
protected double principleAmount;
protected int ageofACHolder;
protected double interestAmount ;
protected double totalAmount;
abstract double calculateInterest();
public void getDetails()
{
System.out.println("Details: ");
System.out.printf("Principle Amount: %.0f\n",principleAmount);
System.out.printf("Interest Rate: %.2f", interestRate);
System.out.println("%");
System.out.printf("Interest Amount: %.0f\n", interestAmount);
System.out.printf("Total Amount: %.0f\n", totalAmount);
}
}

SBACCOUNT CLASS:
package com.Exp3;
import java.util.Scanner;
public class SBAcount extends Account
{
String typeOfAcount;
Scanner sk = new Scanner(System.in);
double calculateInterest()

16 | P a g e
{
while(true)
{
try
{
System.out.print("Enter the Principle Amount: ");
principleAmount = sk.nextDouble();
if (principleAmount <= 0)
{
throw new PrincipleAmountInvalid();
}
break;
}
catch (PrincipleAmountInvalid e)
{
System.out.println(e.getMessage());
} catch (Exception e)
{
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
while(true) {
try {
System.out.print("Enter the Account Type: ");
typeOfAcount = sk.next();
typeOfAcount = typeOfAcount.toLowerCase(Locale.ROOT);
if (typeOfAcount.equals("nri") == typeOfAcount.equals("normal")) {
throw new InvalidAccountType();
}
break;
} catch (InvalidAccountType e) {
e.getMessage();
}
}
if(typeOfAcount.equals("NRI"))
{
interestRate = 6;
}
else
{
interestRate = 4;
}
interestAmount = (principleAmount*interestRate) / 100;
totalAmount = interestAmount + principleAmount;
return interestAmount;
}
}

17 | P a g e
FDACCOUNT CLASS:
package com.Exp3;
import java.util.Scanner;
public class FDAccount extends Account
{
private int noOfDays;
Scanner sk = new Scanner(System.in);
double calculateInterest()
{
while(true)
{
try
{
System.out.print("Enter the Principle Amount: ");
principleAmount = sk.nextDouble();
if (principleAmount <= 0)
{
throw new PrincipleAmountInvalid();
}
break;
}
catch (PrincipleAmountInvalid e)
{
System.out.println(e.getMessage());
} catch (Exception e)
{
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
while(true)
{
try
{
System.out.print("Enter the Age of the Account Holder: ");
ageofACHolder = sk.nextInt();
if (ageofACHolder <= 0 || ageofACHolder >= 150)
{
throw new AgeInvalid();
}
break;
}
catch (AgeInvalid e)
{
System.out.println(e.getMessage());
} catch (Exception e)
{

18 | P a g e
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
while(true) {
try {
System.out.print("Enter the Maturity Period (in Days): ");
noOfDays = sk.nextInt();
if (noOfDays < 7) {
throw new MaturityPeriodInvalid();
}
break;
} catch (MaturityPeriodInvalid e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
if(principleAmount < 10000000)
{
if (noOfDays >= 7 && noOfDays <= 14) {
interestRate = 4.50f;
} else if (noOfDays >= 15 && noOfDays <= 29) {
interestRate = 4.75f;
} else if (noOfDays >= 30 && noOfDays <= 45) {
interestRate = 5.50f;
} else if (noOfDays >= 45 && noOfDays <= 60) {
interestRate = 7.00f;
} else if (noOfDays >= 61 && noOfDays <= 184) {
interestRate = 7.50f;
} else {
interestRate = 8.00f;
}
if(ageofACHolder >= 50)
{
interestRate = interestRate + 0.5;
}
interestAmount = ((interestRate)*principleAmount)/100;
}
else
{
if (noOfDays >= 7 && noOfDays <= 14) {
interestRate = 6.50f;
} else if (noOfDays >= 15 && noOfDays <= 29) {
interestRate = 6.75f;
} else if (noOfDays >= 30 && noOfDays <= 45) {
interestRate = 6.75f;

19 | P a g e
} else if (noOfDays >= 45 && noOfDays <= 60) {
interestRate = 8.00f;
} else if (noOfDays >= 61 && noOfDays <= 184) {
interestRate = 8.50f;
} else {
interestRate = 10.00f;
}
interestAmount = ((interestRate)*principleAmount)/100;
}
totalAmount = principleAmount + interestAmount;
return interestAmount;
}
}

RDACCOUNT CLASS:
package com.Exp3;
import java.util.Scanner;
public class RDAccount extends Account
{
private int noOfMonths;
Scanner sk = new Scanner(System.in);
double calculateInterest()
{
while(true)
{
try
{
System.out.print("Enter the Principle Amount: ");
principleAmount = sk.nextDouble();
if (principleAmount <= 0)
{
throw new PrincipleAmountInvalid();
}
break;
}
catch (PrincipleAmountInvalid e)
{
System.out.println(e.getMessage());
} catch (Exception e)
{
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
while(true)
{
try
{

20 | P a g e
System.out.print("Enter the Age of the Account Holder: ");
ageofACHolder = sk.nextInt();
if (ageofACHolder <= 0 || ageofACHolder >= 150)
{
throw new AgeInvalid();
}
break;
}
catch (AgeInvalid e)
{
System.out.println(e.getMessage());
} catch (Exception e)
{
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
while(true) {
try {
System.out.print("Enter the Maturity Period (in Months): ");
noOfMonths = sk.nextInt();
if (noOfMonths < 6) {
throw new MaturityPeriodInvalidMonths();
}
break;
} catch (MaturityPeriodInvalidMonths e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Exception Caught: " + e.toString() + ". Try Again!!");
sk.nextLine();
}
}
if (noOfMonths >= 6 && noOfMonths <= 8) {
interestRate = 7.50f;
} else if (noOfMonths >= 9 && noOfMonths <= 11) {
interestRate = 7.75f;
} else if (noOfMonths >= 12 && noOfMonths <= 14) {
interestRate = 8.00f;
} else if (noOfMonths >= 15 && noOfMonths <= 17) {
interestRate = 8.25f;
} else if (noOfMonths >= 18 && noOfMonths <= 20) {
interestRate = 8.50f;
} else {
interestRate = 8.75f;
}
if(ageofACHolder >= 50)
{
interestRate = interestRate + 0.5;

21 | P a g e
}
interestAmount = ((interestRate)*principleAmount)/100;
totalAmount = principleAmount + interestAmount;
return interestAmount;
}
}

MAIN CLASS:
package com.Exp3;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
boolean stat1 = true;
int input1;
Scanner sk = new Scanner(System.in);
SBAcount obj_of_sbaccount = null;
FDAccount obj_of_fdaccount = null;
RDAccount obj_of_rdaccount = null;
double result;
while(stat1)
{
System.out.println("\nPress 1: To calculate Interest Amount of SB Account");
System.out.println("Press 2: To Display the detailed info of SB Account");
System.out.println("Press 3: To calculate Interest Amount of FD Account");
System.out.println("Press 4: To Display the detailed info of FD Account");
System.out.println("Press 5: To calculate Interest Amount of RD Account");
System.out.println("Press 6: To Display the detailed info of RD Account");
System.out.println("Press 7: To Terminate");
System.out.print("Input: ");
input1 = sk.nextInt();
switch (input1)
{
case 1:
obj_of_sbaccount = new SBAcount();
result = obj_of_sbaccount.calculateInterest();
System.out.println("The Interest Amount is " + result);
System.out.print("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
case 2:
if(obj_of_sbaccount == null)
{
System.out.println("The Object of SB Account is not Initialized. Initialize it first by pressing
2 in the Main Menu.");
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}

22 | P a g e
break;
}
obj_of_sbaccount.getDetails();
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
case 3:
obj_of_fdaccount = new FDAccount();
result = obj_of_fdaccount.calculateInterest();
System.out.println("The Interest Amount is " + result);
System.out.print("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
case 4:
if(obj_of_fdaccount == null)
{
System.out.println("The Object of FD Account is not Initialized. Initialize it first by pressing
3 in the Main Menu.");
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
}
obj_of_fdaccount.getDetails();
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
case 5:
obj_of_rdaccount = new RDAccount();
result = obj_of_rdaccount.calculateInterest();
System.out.println("The Interest Amount is " + result);
System.out.print("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
case 6:
if(obj_of_rdaccount == null)
{
System.out.println("The Object of FD Account is not Initialized. Initialize it first by pressing
3 in the Main Menu.");
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
}
obj_of_rdaccount.getDetails();
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
case 7:
System.out.println("Terminating...");

23 | P a g e
stat1 = false;
break;
default:
System.out.println("You have Entered Invalid input. Try Again!!!");
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e) {}
break;
}
}
}
}

CUSTOMEXCEPTIONS CLASS:
package com.Exp3;
class CustomExceptions // Dummy. Only for Name
{
}
class MaturityPeriodInvalid extends Exception
{
public String getMessage()
{
return "The Maturity Period should be at least 7 days. Try Again!!";
}
}
class AgeInvalid extends Exception
{
public String getMessage()
{
return "The Age should be greater than 0 and less than 150";
}
}
class PrincipleAmountInvalid extends Exception
{
public String getMessage()
{
return "The Principle Amount should be greater than 0. Try Again !!";
}
}
class MaturityPeriodInvalidMonths extends Exception
{
public String getMessage()
{
return "The Maturity Period should be at least 6 Months. Try Again!!";
}
}
class InvalidAccountType extends Exception
{
public String getMessage()

24 | P a g e
{
return "The Account type should be either 'Normal' or 'NRI'. Try Again!!";
}
}

4. Output:
Modules:

Running Code Output:

25 | P a g e
26 | P a g e
27 | P a g e
28 | P a g e
Exception Handling Outputs:

29 | P a g e
30 | P a g e
Experiment 1.4

Create a menu-based Java application with the following options


1. Add an Employee
2. Display All
3. Exit If option 1 is selected, the application should gather details of the employee like
employee name, employee id, designation, and salary and store it in a file. If option 2 is
selected, the application should display all the employee details. If option 3 is selected the
application should exit.

1. Aim/Overview of the practical:


We need to create a menu-based application to store details of employees like employee id,
name, designation, and, salary and we should store all these details in a file.

2. Task to be done:
In this experiment, we will use concepts like serialization and deserialization to implement
the above mentions problem.

3. Code:
package com.Exp4;
import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
//Making the class Serializable to convert the object into a byte stream
class Employee implements Serializable
{
String eName;
String eID;
String eDesignation;
int eAge;
long salary;
public Employee()
{
eName = null;
eID = null;
eDesignation = null;
salary = 0;
}
public Employee(String name, String id, String designation, int age, long sal)
{
eName = name;
eID = id;
eDesignation = designation;
eAge = age;
salary = sal;
}

31 | P a g e
// Declaring a default function to display details in string format
public String toString()
{
return "ID = " + eID + ", Name = " + eName + ", Age = " + eAge + ", Salary = " + salary + ",
Designation = "+ eDesignation;
}
}
public class Main
{
//Creating a LinkedList to store Employee objects
List<Employee> allEmployee = new LinkedList<>();
static Scanner sk = new Scanner(System.in);
public static void main(String args[])
{
int input1;
Main obj = new Main();
boolean stat = true;
String tempName;
while(stat)
{
System.out.println("Press 1: To Add an Employee");
System.out.println("Press 2: To Display All");
System.out.println("Press 3: To write all the entered Employee data on a file");
System.out.println("Press 4: To read Employee data from a file");
System.out.println("Press 5: To Exit");
System.out.print("Input:- ");
input1 = sk.nextInt();
switch (input1)
{
case 1:
obj.addEmployee();
break;
case 2:
obj.displayEmployee(obj.allEmployee);
break;
case 3:
System.out.print("Enter the file name: ");
tempName = sk.next();
obj.writeFile(tempName);
break;
case 4:
System.out.print("Enter the file name: ");
tempName = sk.next();
obj.readFile(tempName);
break;
case 5:
System.out.println("Terminating");
stat = false;

32 | P a g e
break;
}
}
}
public void addEmployee()
{
String tempName, tempID, tempDesignation;
int tempAge;
long tempSalary;
while(true)
{
try
{
System.out.print("Enter the Name of the Employee: ");
tempName = sk.next();
sk.nextLine();
System.out.print("Enter the ID of the Employee: ");
tempID = sk.next();
System.out.print("Enter the Designation of the Employee: ");
tempDesignation = sk.next();
System.out.print("Enter the Age of the Employee: ");
tempAge = sk.nextInt();
System.out.print("Enter the Salary of the Employee: ");
tempSalary = sk.nextLong();
allEmployee.add(new Employee(tempName, tempID, tempDesignation, tempAge,
tempSalary));
break;
}
catch (Exception e)
{
System.out.println("Exception Caught!! "+ e.toString());
System.out.println("Please, Try Again!!. Enter to continue...");
try { System.in.read();} catch(Exception e1) {}
}
}
System.out.println("Successfully Added...");
}
public void displayEmployee(List<Employee>allEmployeetemp)
{
try
{
Iterator it = allEmployeetemp.iterator();
System.out.println("Employees Details");
//Iterating through the list
while(it.hasNext())
{
System.out.println("" + it.next());
}

33 | P a g e
System.out.println("All details are displayed");
}
catch (Exception e)
{
System.out.println("Exception Caught. " + e.toString());
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e1) {}
}
}
public void writeFile(String name)
{
//Creating object of type File to store the file
File fileObj = new File("C:\\Users\\MARK\\OneDrive\\Documents\\Chandigarh University
Sem 4\\Project based learning JAVA\\Exp 4\\" + name);
try
{
// Creating File Output Stream in order to write onto a file
FileOutputStream fileStream = new FileOutputStream(fileObj);
// Creating Object Output Stream to write the object onto the file
ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
objStream.writeObject(allEmployee);
System.out.println("Data stored successfully");
}
catch (Exception e)
{
System.out.println("Exception Caught. " + e.toString());
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e1) {}
}
}
public void readFile(String name)
{
//Creating object of type File to store the file
File fileObj = new File("C:\\Users\\MARK\\OneDrive\\Documents\\Chandigarh University
Sem 4\\Project based learning JAVA\\Exp 4\\" + name);
try
{
// Creating File Input Stream in order to read a file
FileInputStream fileStream = new FileInputStream(fileObj);
// Creating Object Input Stream to read the object from the file
ObjectInputStream objStream = new ObjectInputStream(fileStream);
allEmployee.clear();
allEmployee = (List<Employee>)objStream.readObject();
displayEmployee(allEmployee);
System.out.println("Data stored successfully");
}
catch (Exception e)
{

34 | P a g e
System.out.println("Exception Caught. " + e.toString());
System.out.println("Enter to continue...");
try { System.in.read();} catch(Exception e1) {}
}
}
}

4. Output:

Displaying the location and we can see that there is no file created to store the data.

35 | P a g e
36 | P a g e
37 | P a g e
We can see that, after the execution, the EmployeeData file is created. So, next time we want
to access the previously stored data, we can use this file.

Running the program a second time, this time we will access previously stored data using the
EmployeeData file.

38 | P a g e
Experiment -2.1

Create a program to set the view of keys from the java hash table and create a program to
show the usage of the sets of collection interface.

1. Aim/Overview of the practical:


(a) Create a program to set the view of Keys from the Java Hash table.
(b) Create a program to show the usage of the Sets of Collection interface.

2. Task to be done:
• We need to create a Java Hash table and store some values with keys and display them
using an iterator.
• We need to import the collection package (which is present in the java.util package). And
implement it for data structures like sets, lists, etc.

3. Code:
(Q1)
package com.Exp5;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
public class Main
{
public static void main(String args[])
{
// Creating a hash table object with key data type are Integer and value data type as String
Hashtable<Integer, String> htbl = new Hashtable<Integer, String>();
// Adding Elements into the Hash Table
//Note: The Hashtable is internally sorted, so irrespective of input order, all the key-value
pairs will be
// sorted into particular order
htbl.put(1, "John");
htbl.put(3, "Michael");
htbl.put(2, "Peter");
htbl.put(6, "Fin");
htbl.put(10, "George");
System.out.println("Display in the Key - Value pairs using Iterators:");
Iterator it1 = htbl.keySet().iterator();
Iterator it2 = htbl.values().iterator();
while(it1.hasNext())
{
System.out.println(it1.next()+ " - " + it2.next());
}
Enumeration e1 = htbl.keys();
System.out.println("\nDisplaying the Keys using enumerator");
while(e1.hasMoreElements())
{
39 | P a g e
System.out.println(e1.nextElement());
}
}
}

(Q2)
package com.Exp5;
import java.util.*;
class Main
{
public static void main(String args[])
{
//Here we are initialing an object of type Set with HashSet
//In general, HashSet class implements Set class. So, the statement that is written shows the
// Abstraction concept
Set<String> s1 = new HashSet<String>();
s1.add("B");
s1.add("C");
s1.add("A");
s1.add("C");
s1.add("D");
System.out.println("Set 1: "+ s1);
List l1 = new ArrayList();
l1.add("B");
l1.add("C");
l1.add("A");
l1.add("C");
l1.add("D");
// We can see that duplicate values are allowed in List data structure
System.out.println("\nDisplaying the List: " + l1);
Set s2 = new HashSet(l1);
System.out.println("\nDisplaying the Set 2 which is created using above list: " + s2);
System.out.println("\nIs Set 1 equal to Set 2: " + s1.equals(s2));
s1.remove("A");
System.out.println("\nElement 'A' is removed from set 1");
System.out.println("\nIs Set 1 equal to Set 2: " + s1.equals(s2));
System.out.println("\nSize of Set 1 = " + s1.size());
System.out.println("Size of Set 2 = " + s2.size());
System.out.println("\nDisplaying the Set 1 using iterator:");
Iterator it = s1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
System.out.println("\nDisplaying the Set 1 using for each loop:");
for (String i: s1)

40 | P a g e
{
System.out.println(i);
}
//Type casting using Sets
String arr[] = (String[]) s2.toArray(new String[s2.size()]);
System.out.println("\nDisplaying the Set 2 after type casting into String: ");
for(String j: arr)
{
System.out.println(j);
}
}
}

4. Output:

41 | P a g e
Output of Q1

Outputs of Q2

42 | P a g e
Experiment -2.2

Write a Program to perform the basic operations like insert, delete, display, and search in the
list. List contains String object items where these operations are to be performed.

1. Aim/Overview of the practical:


Write a Program to perform the basic operations like insert, delete, display, and search in the
list. List contains String object items where these operations are to be performed.

2. Task to be done:
We need to demonstrate the basic operations like insertion, deletion, displaying, etc. on list
data structure and we need to use the data type of the list as String.

3. Code:
package com.Exp6;
import java.util.*;
public class Main
{
public static void main(String args[])
{
List<String> l1 = new ArrayList<String>();
l1.add("A");
l1.add("B");
l1.add("C");
l1.add("D");
l1.add(null);
l1.add("A");
System.out.println("Displaying the List: " + l1);
String str1 = l1.get(3);
System.out.println("\nAccessing the value at index 3: " + str1);
System.out.println("\nIs 'C' present in the list? : " + l1.contains("C"));
Iterator it = l1.iterator();
System.out.print("\nDisplaying the List using Iterator: ");
while(it.hasNext())
{
System.out.print(it.next()+ " ");
}
l1.remove(null);
System.out.print("\n\nDisplaying the list after removing the null element: ");
System.out.println(l1);
l1.remove(2);
System.out.println("\nDisplaying the list after removing the element based on index: " + l1);
System.out.println("\nAgain removing the element at index 2. If it is successful then it will
return true, else false: " + l1.remove("C"));
System.out.println("\nDisplaying the size of the list: " + l1.size());
l1.clear();
System.out.println("\nDisplaying the size of the list after clearing the list: " + l1.size());
43 | P a g e
}
}

4. Output:

44 | P a g e
Experiment -2.3

Write a Java multi-threaded program to implement the tortoise and hare story. Make the hare
sleep in the mid of the way and let the tortoise win.

1. Aim/Overview of the practical:


Write a Java multi-threaded program to implement the tortoise and hare story. Make the hare
sleep in the mid of the way and let the tortoise win.

2. Task to be done:
We need to use the concept of multi-threading to solve this problem. We need to create a
separate thread for hare and tortoise and execute them parallelly. And in between make the
hare sleep so that the tortoise will win the race.

3. Code:
import java.util.Scanner;
class hare extends Thread // Class for Hare
{
int dist; // Distance for the race
public hare(int distance, String thread_name) // Initializing required values
{
dist = distance;
super.setName(thread_name);
}
public void run() // Overriding run function
{
System.out.println(this.getName() + " is Started");
int dist_covered = 0, sleep_point;
//Initializing the sleep_point or midpoint
if(dist % 2 == 0)
{
sleep_point = (dist/2);
}
else
{
sleep_point = (dist/2) + 1;
}
while(dist_covered < dist-1)
{
dist_covered++;
if(dist_covered < dist && dist_covered != sleep_point) // Displaying the distance covered
{
System.out.println("Distance covered by " + this.getName() + " = " + dist_covered);
}
else
{
System.out.println(this.getName() + " is sleeping now. Distance covered till now = " +
dist_covered);

45 | P a g e
try
{
Thread.sleep(1000); // Hare thread is set to sleep for 1 sec
}
catch (Exception e)
{
}
System.out.println(this.getName() + " wakes up again");
}
}
System.out.println(this.getName() + " finished the race!!!");
}
}
class tortoise extends Thread // Class for tortoise
{
int dist;
public tortoise(int distance, String thread_name) // Initializing required values
{
dist = distance;
super.setName(thread_name);
}
public void run()
{
System.out.println(this.getName() + " is Started");
int dist_covered = 0;
while(dist_covered < dist)
{
dist_covered++;
if(dist_covered == dist)
{
System.out.println(this.getName() + " finished the race!!!");
}
else
{
//Displaying the distance covered
System.out.println("Distance covered by " + this.getName() + " = " + dist_covered);
try
{
Thread.sleep(10); // Tortoise thread is kept into sleep for 10 millisecond. Because in hare
class
// there are more operations, due to that the tortoise thread is finishing even before the hare
goes
//to sleep. So, according to the story, as the tortoise is slower, we will make the tortoise
thread
//slower
}
catch (Exception e)
{

46 | P a g e
}
}
}
}
}
public class Main
{
public static void main(String args[])
{
int distance = 0;
Scanner sk = new Scanner(System.in);
System.out.print("Enter the distance for the race between Hare and Tortoise: ");
distance = sk.nextInt(); // Inputting the distance from the user
//Creating required objects
hare thread1 = new hare(distance, "Hare");
tortoise thread2 = new tortoise(distance, "Tortoise");
//Starting both threads
thread1.start();
thread2.start();
}
}

4. Output:

47 | P a g e
48 | P a g e
Experiment -3.1

Create a console-based application using Java as frontend and Oracle as backend for their
Inventory and Sales maintenance.

1. Aim/Overview of the practical:


Create a console based application using Java as frontend and Oracle as backend for their
Inventory and Sales maintenance.

2. Task to be done:
We need to connect Java to the database using JDBC driver and using Java console as the
Front end, we need to insert or display the data from the database.

3. Code:
package Exp8;
import java.sql.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver"); // Loading the JDBC Driver
String url, uname, password;
url = "jdbc:mysql://localhost:3306/product_inventory_list";
uname = "root";
password = "Java123Language";
con = DriverManager.getConnection(url, uname, password);
}
catch(Exception e)
{
System.out.println(e.toString());
System.exit(0);
}
Scanner sk = new Scanner(System.in);
Boolean stat = true;
int input1;
String custo_name;
String prod_name;
int quantity;
while (stat)
{
System.out.println("\nPress 1: To insert data into the Database");
System.out.println("Press 2: To display the data in the Database");
System.out.println("Press 3: To Terminate");
System.out.print("Input: ");

49 | P a g e
input1 = sk.nextInt();
switch(input1)
{
case 1:
System.out.print("\nEnter the name of the Customer: ");
custo_name = sk.next();
System.out.print("Enter the name of the Product: ");
prod_name = sk.next();
System.out.print("Enter quantity of the Product: ");
quantity = sk.nextInt();
try
{
PreparedStatement ps = con.prepareStatement("insert into inventorylist values(?,?,?)");
ps.setString(1, custo_name);
ps.setString(2, prod_name);
ps.setInt(3, quantity);
ps.executeUpdate();
}
catch(Exception e)
{
System.out.println(e.toString());
System.exit(0);
}
System.out.println("\nThe data is added into the Database successfully\n");
break;
case 2:
try
{
Statement s = con.createStatement();
ResultSet r = s.executeQuery("select * from inventorylist");
while(r.next())
{
System.out.println(r.getString(1) + " - " + r.getString(2) + " - " + r.getInt(3));
}
}
catch(Exception e)
{
System.out.println(e.toString());
System.exit(0);
}
System.out.println("\nThe data is displayed Successfully\n");
break;
case 3:
System.out.println("Terminatting...");
System.exit(0);
break;
default:
System.out.println("\nInvalid input. Try again!!\n");

50 | P a g e
break;
}
}
}
}

4. Output:

Displaying the empty database which is created in mySql workbench.

51 | P a g e
Using Java console as front-end, we are inserting and displaying the data from the database.

Displaying the database after inserting the values.

52 | P a g e
Experiment -3.2

Create an application for Online Auction using HTML and Servlet. Use a database to store
and retrieve the record.

1. Aim/Overview of the practical:


Create an application for Online Auction using HTML and Servlet. Use a database to store
and retrieve the record.

2. Task to be done:
We need to use the concept of Java Servlets to solve this problem. We need to create a web
page using HTML and by using an XML file, we need to link it with the Servlet. In the
Servlet, we will use the JDBC driver to connect it with the database.

3. Code:
Servlet Code:
package com.Exp_9;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.http.*;
public class Java_Servlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
NullPointerException, IOException
{
String bidder_name = null;
String product_name = null;
String bid_value = null;
try
{
bidder_name = req.getParameter("name");
product_name = req.getParameter("products");
bid_value = req.getParameter("bid_val");
}
catch(Exception e)
{
if(bidder_name == null)
{
bidder_name = "NA";
}
if(product_name == null)
{
product_name = "NA";
}
if(bid_value == null)
{
bid_value = "0";

53 | P a g e
}
}
Connection con= null;
PreparedStatement ps = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
String url, uname, password;
url = "jdbc:mysql://localhost:3306/auction_database";
uname = "root";
password = "Java123Language";
con = DriverManager.getConnection(url, uname, password);
Statement stmt=con.createStatement();
ps=con.prepareStatement("insert into auction_data values(?,?,?)");
ps.setString(1,bidder_name);
ps.setString(2,product_name);
ps.setString(3,bid_value);
ps.executeUpdate();
}
catch(Exception e)
{
System.out.println(e.toString());
System.exit(0);
}
try
{
PrintWriter out = res.getWriter();
ResultSet rs= ps.executeQuery("select * from auction_data");
while(rs.next())
{
out.println("<br>Your data is : "+rs.getString(1)+" - "+rs.getString(2)+" - "+rs.getInt(3));
}
con.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}

HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>ONLINE AUCTION</title>
</head>
<body>

54 | P a g e
<form action="store_res">
<h1>ONLINE AUCTION</h1>
Bidder Name:<input type="text" name="name"/><br/><br/>
Product:
<label for="products">Select the Product:</label>
<select name="products">
<option value="DELL">DELL</option>
<option value="HP">HP</option>
<option value="SONY">SONY</option>
<option value="LENOVO">LENOVO</option>
</select>
<br/><br/>
Bid Value:<input type="number" name="bid_val"/><br/><br/>
<input type="submit" onclick="input_sucess()"/>
<input type="reset"/>
<script>
function input_sucess() {
alert("The data is inputted");
}
</script>
</form>
</body>
</html>
XML Code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/j2ee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>store</servlet-name>
<servlet-class>com.Exp_9.Java_Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>store</servlet-name>
<url-pattern>/store_res</url-pattern>
</servlet-mapping>
</web-app>

55 | P a g e
4. Output:

Displaying the empty, database table (Table name = auction_data)

This is the Webpage, here user needs to input the values.

56 | P a g e
After clicking on the submit button, the database entries are displayed.

57 | P a g e
Here, we can see that the input is stored in the database also.

58 | P a g e
59 | P a g e
Here, we can see that all entries from the webpage are stored successfully.

60 | P a g e
Experiment - 3.3

Create a JSP application with a facility to


(1) Login to the application
(2) Register a new user
(3) Change password for an existing user.

1. Aim/Overview of the practical:


Create a JSP application with a facility to (1) Login to the application (2) Register a new user
and (3) Change password for an existing user.

2. Task to be done:
We need to use JSP (Java Server Pages) concept to solve this problem. We need to create
webpages using HTML and after than we need to link respective JSP to the respective HTML
file. Next, by using JSP, we will connect with the database.

3. Code:
HOME_PAGE.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Users Database</title>
</head>
<body>
Click on LOGIN to open your account<br>
<a href="Login_Page.html" >LOGIN</a>
<br><br>
Click on REGISTER to register your account<br>
<a href="Register_Page.html">REGISTER</a>
</body>
</html>

LOGIN_PAGE.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>LOGIN</title>
</head>
<body>
<h1>Login Page</h1>
<form action = "LOGIN.jsp">
USER NAME: <input type="text" name="user_name"><br>
PASSWORD: <input type="password" name=user_password><br>
<input type="submit" value="Login">
<input type="reset">
<br>

61 | P a g e
<a href="Forgot_Password_page.html">Forgot Password</a>
<br>
<br>
<a href="Home_Page.html">Click to go to Home Page</a>
</form>
</body>
</html>

LOGIN.JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
import="java.sql.*"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Account</title>
</head>
<body>
<%
String uname = request.getParameter("user_name");
String password = request.getParameter("user_password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/user_details","root","Java123La
nguage");
PreparedStatement stmt = con.prepareStatement("select password from user_information
where user_name=?");
stmt.setString(1, uname);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
if((rs.getString(1)).equals(password))
{
out.println("<h1>Login Successful</h1>");
stmt = con.prepareStatement("select user_name, password, full_name, email, age, city from
user_information where user_name=?");
stmt.setString(1, uname);
rs = stmt.executeQuery();
if(rs.next())
{
out.println("User Name: " + rs.getString(1) + "<br>");
out.println("Password: " + rs.getString(2) + "<br>");
out.println("Full Name: " + rs.getString(3) + "<br>");
out.println("Email Address: " + rs.getString(4) + "<br>");
out.println("Age: " + rs.getString(5) + "<br>");

62 | P a g e
out.println("City: " + rs.getString(6) + "<br>");
out.println("<br><br><a href=\"Login_Page.html\" >Click here to Logout</a>");
}
}
else
{
out.println("<h1> Incorrect password </h1>");
out.println("<a href=\"Login_Page.html\" >Click here to reload</a>");
}
}
else
{
out.println("<h1> User name not found </h1>");
out.println("<a href=\"Login_Page.html\" >Click here to reload</a>");
}
}
catch(Exception e)
{
out.println(e.toString());
}
%>
</body>
</html>

FORGOT_PASSWORD_PAGE.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Forgot_Password.jsp">
Enter the User Name <input type="text" name="uname">
Enter the new password <input type="text" name="new_pass">
<input type="submit" value="reset">
</form>
</body>
</html>
Forgot_Password.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
import="java.sql.*"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Password Reset</title>

63 | P a g e
</head>
<body>
<%
String uname = request.getParameter("uname");
String new_password = request.getParameter("new_pass");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/user_details","root","Java123La
nguage");
PreparedStatement stmt = con.prepareStatement("select user_name from user_information
where user_name=?");
stmt.setString(1, uname);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
stmt = con.prepareStatement("update user_information set password=? where
user_name=?");
stmt.setString(1, new_password);
stmt.setString(2, uname);
stmt.executeUpdate();
out.println("<h1> Your Password is updated Successfully </h1>");
out.println("<br><a href=\"Login_Page.html\" >Click here to go to Login page</a>");
}
else
{
out.println("<h1> User name not found </h1>");
out.println("<a href=\"Login_Page.html\" >Click here to reload</a>");
}
}
catch(Exception e)
{
out.println(e.toString());
}
%>
</body>
</html>

REGISTER_PAGE.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration</title>
</head>
<body>
<h1>Registration Page</h1>

64 | P a g e
<form action=Registration.jsp>
Enter the User Name <input type="text" name="uname"> <br>
Enter the Password <input type="password" name="password"> <br>
Confirm the Password <input type="password" name="password_check"> <br>
Enter your Full name <input type="text" name="fname"> <br>
Enter your Email ID <input type="text" name="email"> <br>
Enter your Age <input type="text" name="age"> <br>
Enter your City <input type="text" name="city"> <br>
<input type="submit" value= "Create Account"> <br>
<input type="reset">
<br>
<br>
<a href="Home_Page.html">Click to go to Home Page</a>
</form>
</body>
</html>

REGISTRATION.JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
import="java.sql.*"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String password = request.getParameter("password");
String password_check = request.getParameter("password_check");
if(password.equals(password_check))
{
String uname = request.getParameter("uname");
String full_name = request.getParameter("fname");
String age = request.getParameter("age");
String city = request.getParameter("city");
String email = request.getParameter("email");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/user_details","root","Java123La
nguage");
PreparedStatement stmt = con.prepareStatement("insert into user_information values( ?, ?, ?,
?, ?, ?)");
stmt.setString(1, uname);
stmt.setString(2, password);

65 | P a g e
stmt.setString(3, full_name);
stmt.setString(4, email);
stmt.setString(5, age);
stmt.setString(6, city);
stmt.executeUpdate();
out.println("<h1> New Account created Successfully </h1>");
out.println("Receipt:<br>");
stmt = con.prepareStatement("select user_name, password, full_name, email, age, city from
user_information where user_name=?");
stmt.setString(1, uname);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
out.println("User Name: " + rs.getString(1) + "<br>");
out.println("Password: " + rs.getString(2) + "<br>");
out.println("Full Name: " + rs.getString(3) + "<br>");
out.println("Email Address: " + rs.getString(4) + "<br>");
out.println("Age: " + rs.getString(5) + "<br>");
out.println("City: " + rs.getString(6) + "<br>");
out.println("<br><br><a href=\"Home_Page.html\" >Click here to go to Home_Page</a>");
}
}
catch(Exception e)
{
out.println(e.toString());
}
}
else
{
out.println("<h1>Password and Confirm Password are mismatched. Try Again</h1>");
out.println("<a href=\"Register_Page.html\">Click to Reload </a>");
}
%>
</body>
</html>

66 | P a g e
4. Output:
Displaying the database and showing that it is empty.

This is the Home Page for this experiment. If we click on LOGIN then the login page will
open and if we click on REGISTER then the registration page will open.

67 | P a g e
This what a registration page looks like

Creating a new Account

68 | P a g e
This is the Acknowledgement that we will get after clicking on Create Account.

We can see that the database is updated.

69 | P a g e
Adding some new accounts.

70 | P a g e
Displaying all inputted accounts in the mySQL.

This is how a Login Page looks like

71 | P a g e
After Logging in with suitable credentials.

72 | P a g e
If we click on Forgot Password, this page will be displayed. Here, we are changing the old
password 123 of mohit007 into 246.

73 | P a g e
We can see in the database that the password of mohit007 is updated.

If we try to login with a username which doesn't exist is the database,

74 | P a g e
This acknowledgement will be displayed.

If we type wrong password,

75 | P a g e
Then this acknowledgment is displayed.

76 | P a g e

You might also like