OOP Lab Manual (1) - 240821 - 103634
OOP Lab Manual (1) - 240821 - 103634
:1(a)
DATE: SEQUENTIAL SEARCH
AIM:
To develop a Java application to search an element in an array using sequential search
algorithm.
ALGORITHM:
PROGRAM:
LinearSearch.java
public class LinearSearch
{
static intsearch(intarr[], int n, int s)
{
for (inti = 0; i< n; i++)
{
if (arr[i] == s)
return i;
}
return -1;
}
public static void main(String[] args)
{
int[] arr = { 3, 4, 1, 7, 5 };
int n = arr.length;
int s = 4;
int index = search(arr, n, s);
if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at index " + index);
}
1
}
OUTPUT:
D:\Java\CS3381>javac LinearSearch.java
D:\Java\CS3381>java LinearSearch
Element found at index 1
RESULT:
Thus, the Java application to perform sequential search was implementedand executed
successfully.
2
EX.NO.:1(b)
DATE: BINARY SEARCH
AIM:
To develop a Java application to search an element in an array using binary search
algorithm.
ALGORITHM:
PROGRAM:
BinarySearch.java
class BinarySearch
{
public static intbinarySearch(intarr[], int first, int last, int key)
{
if (last>=first)
{
int mid = (first +last)/2;
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] >key)
{
return binarySearch(arr, first, mid-1, key);
}
else
{
return binarySearch(arr, mid+1, last, key);
3
}
}
return -1;
}
public static void main(String args[])
{
intarr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
int result = binarySearch(arr,0,last,key);
if (result == -1)
System.out.println("Element is not found!");
else
System.out.println("Element is found at index: "+result);
}
}
OUTPUT:
D:\Java\CS3381>javac BinarySearch.java
D:\Java\CS3381>java BinarySearch
Element is found at index: 2
D:\Java\CS3381>
RESULT:
Thus, the Java application to perform binary search was implemented and executed
successfully.
4
EX.NO.:1(c)
DATE: INSERTION SORT
AIM:
To develop a Java application to sort an array of elements in ascending order using insertion
sort.
ALGORITHM:
PROGRAM:
InsertionSort.java
5
{
if(x<num[j])
{
num[j+1]=num[j];
}
else
{
break;
}
j=j-1;
}
num[j+1]=x;
}
System.out.print("\n\nArray after Insertion Sort\n");
for(i=0; i<num.length; i++)
{
System.out.print(num[i]+" ");
}
}
}
OUTPUT:
D:\Java\CS3381>javac InsertionSort.java
D:\Java\CS3381>java InsertionSort
Array before Insertion Sort
12 9 37 86 2 17 5
Array after Insertion Sort
2 5 9 12 17 37 86
D:\Java\CS3381>
RESULT:
Thus, the Java application to sort an array of N elements using insertion sort was
implemented and executed successfully.
6
EX.NO.:1(d)
DATE: SELECTION SORT
AIM:
To develop a Java application to sort an array of elements in ascending order using selectin
sort.
ALGORITHM:
PROGRAM:
SelectionSort.java
7
}
}
int temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
public static void main(String[] args)
{
int[] arr= {15,21,6,3,19,20};
System.out.println("Elements in the array before Sorting");
for(int i:arr)
System.out.print(i+" ");
selectionsort(arr);
System.out.println("\nElements in the array after Sorting");
for(int i:arr)
System.out.print(i+" ");
}
}
OUTPUT:
D:\Java\CS3381>javac SelectionSort.java
D:\Java\CS3381>java SelectionSort
Elements in the array before Sorting
15 21 6 3 19 20
Elements in the array after Sorting
3 6 15 19 20 21
D:\Java\CS3381>
RESULT:
Thus, the Java application to sort an array of N elements using selection sort was
implemented and executed successfully.
8
EX.NO.: 2(a)
DATE: STACK DATA STRUCTURE
AIM:
To develop a Java program to implement stack data structure using classes and objects.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class named Stack and declare the instance variables st[], top,
maxsize as private.
Step3:Use constructor to allocate memory space for the array and initialize top as -1.
Step 4: Define methods such as isFull(), isEmpty(), push(), pop() and printStack();
Step 5: Push Operation
Step 5.1: Check whetherstack has some space or stack is full.
Step 5.2: If the stack has no space then display “overflow” and exit.
Step 5.3: If the stack has space then increase top by 1 to point next empty space.
Step 5.4: Add element to the new stack location, where top is pointing.
Step 5.5: Push operation performed successfully.
Step 6: Pop operation
Step 6.1: Check whether stack has some element or stack is empty.
Step 6.2: If the stack has no element means it is empty then display “underflow”
Step 6.3: If the stack has some element, accesses the data element at which top is
pointing.
Step 6.4: Decrease the value of top by 1.
Step 6.5: Pop operation performed successfully.
Step 7: PrintStack operation
Step 7.1:Check whether stack has some element or stack is empty.
Step 7.2: If the stack has no element means it is empty then display “underflow”.
Step 7.3: If the stack has some element, traverse the array from top to bottom and
display the elements.
Step 8: Define the main() method
Step 9: Create object of Stack class.
Step 10: Display the menu and get the user choice and invoke appropriate method.
9
Step 11: Stop the program.
PROGRAM:
Stack.java
import java.util.Scanner;
public class Stack
{
private intmaxsize, top;
private int[] st;
public Stack(int size)
{
maxsize = size;
st = new int[maxsize];
top = -1;
}
booleanisEmpty()
{
return top==-1;
}
booleanisFull()
{
return top==maxsize-1;
}
public void push(int element)
{
if(isFull())
System.out.println("Overflow");
else
st[++top] = element;
}
public intpop()
{
if(isEmpty())
{
System.out.println("UnderFlow");
return (-1);
}
return (st[top--]);
}
public void printStack()
{
System.out.println("Stack Elements:");
10
for (inti = top; i>=0; i--)
System.out.println(st[i]);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter stack size");
int size=sc.nextInt();
Stack obj = new Stack(size);
while (true)
{
System.out.println("\nSTACK\n*****\n1.PUSH\n2.POP
\n3.Display\n4.EXIT\nEnter your choice");
intch = sc.nextInt();
switch (ch)
{
case 1:
System.out.println("Enter Element");
int n = sc.nextInt();
obj.push(n);
break;
case 2:
System.out.printf("Poped element is %d", obj.pop());
break;
case 3:
obj.printStack();
break;
case 4:
System.exit(0);
default:
System.out.println("Wrong option");
}
}
}
}
OUTPUT:
D:\Java\CS3381>java Stack
Enter stack size
5
STACK
*****
1.PUSH
11
2.POP
3.Display
4.EXIT
Enter your choice
1
Enter Element
12
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
1
Enter Element
34
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
1
Enter Element
56
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
1
Enter Element
78
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
3
Stack Elements:
12
78
56
34
12
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
2
Poped element is 78
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
3
Stack Elements:
56
34
12
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
4
D:\Java\CS3381>
RESULT:
Thus, the Java program to implement stack data structure using classes and objects has
developed and executed successfully.
13
EX.NO.: 2(b)
DATE: QUEUE DATA STRUCTURE
AIM:
To develop a Java program to implement queue data structure using classes and objects.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class named Queue and declare the instance variables items[], front, rear,
maxsize as private.
Step3:Use constructor to allocate memory space for the array and initialize front as -1 and
rear as -1.
Step 4: Define methods such as isFull(), isEmpty(), enQueue(), deQueue() and display();
Step 5: Enqueue Operation
Step 5.1: Check whetherqueue has some space or queue is full.
Step 5.2: If the queue has no space then display “overflow” and exit.
Step 5.3: If the queue has space then increase rear by 1 to point next empty space.
Step 5.4: Add element to the new location, where rear is pointing.
Step 5.5: Enqueue operation performed successfully.
Step 6: Dequeue operation
Step 6.1: Check whether queue has some element or queue is empty.
Step 6.2: If the queue has no element means it is empty then display “underflow”
Step 6.3: If the queue has some element, accesses the data element at which front is
pointing.
Step 6.4: Incrementthe value of front by 1.
Step 6.5:Dequeue operation performed successfully.
Step 7: Displayoperation
Step 7.1:Check whether queue has some element or queue is empty.
Step 7.2: If the stack has no element means it is empty then display “underflow”.
Step 7.3: If the stack has some element, traverse the array from front to rear and
display the elements.
Step 8: Define the main() method
Step 9: Create object of Queue class.
Step 10: Display the menu and get the user choice and invoke appropriate method.
Step 11: Stop the program.
14
PROGRAM:
Queue.java
import java.util.Scanner;
public class Queue
{
private intitems[];
private intmaxsize, front, rear;
Queue(int size)
{
maxsize=size;
items = new int[size];
front = -1;
rear = -1;
}
booleanisFull()
{
if (front == 0 && rear ==maxsize-1)
{
return true;
}
return false;
}
booleanisEmpty()
{
if (front == -1)
return true;
else
return false;
}
void enQueue(int element)
{
if (isFull())
15
{
System.out.println("Queue is full");
}
else
{
if (front == -1)
front = 0;
rear++;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
intdeQueue()
{
int element;
if (isEmpty())
{
System.out.println("Queue is empty");
return (-1);
}
else
{
element = items[front];
if (front >= rear)
{
front = -1;
rear = -1;
}
else
{
front++;
}
return (element);
}
16
}
void display()
{
inti;
if (isEmpty())
{
System.out.println("Empty Queue");
}
else
{
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i<= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter queue size");
int size=sc.nextInt();
Queue obj = new Queue(size);
while (true)
{
System.out.println("\nQUEUE\n*****\n1.ENQUEUE\n2.DEQUEUE\
n3.DISPLAY\n4.EXIT\nEnter your choice");
intch = sc.nextInt();
switch (ch)
{
case 1:
System.out.println("Enter Element");
int n = sc.nextInt();
obj.enQueue(n);
17
break;
case 2:
System.out.printf("Dequeued element is %d", obj.deQueue());
break;
case 3:
obj.display();
break;
case 4:
System.exit(0);
default:
System.out.println("Wrong option");
}
}
}
}
OUTPUT:
D:\Java\CS3381>javac Queue.java
D:\Java\CS3381>java Queue
Enter queue size
5
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
12
Inserted 12
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
18
34
Inserted 34
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
56
Inserted 56
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
78
Inserted 78
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
3
Front index-> 0
Items ->
12 34 56 78
Rear index-> 3
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
2
Poped element is 12
19
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
3
Front index-> 1
Items ->
34 56 78
Rear index-> 3
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
4
D:\Java\CS3381>
RESULT:
Thus, the Java program to implement queue data structure using classes and objects has
developed and executed successfully.
20
EX.NO.: 3
DATE: PAYSLIP GENERATION USING INHERITANCE
AIM:
To develop a java application to generate pay slip for different category of employees using
theconcept of inheritance.
ALGORITHM:
PROGRAM:
PaySlip.java
import java.util.Scanner;
class Employee
{
String Emp_name,Mail_id,Address,Emp_id, Mobile_no;
double BP,GP,NP,DA,HRA,PF,CF;
Scanner get = new Scanner(System.in);
Employee()
{
System.out.println("Enter Name of the Employee:");
Emp_name = get.nextLine();
21
System.out.println("Enter Address of the Employee:");
Address = get.nextLine();
System.out.println("Enter ID of the Employee:");
Emp_id = get.nextLine();
System.out.println("Enter Mobile Number:");
Mobile_no = get.nextLine();
System.out.println("Enter E-Mail ID of the Employee :");
Mail_id = get.nextLine();
}
void display()
{
System.out.println("Employee Name: "+Emp_name);
System.out.println("Employee Address: "+Address);
System.out.println("Employee ID: "+Emp_id);
System.out.println("Employee Mobile Number: "+Mobile_no);
System.out.println("Employee E-Mail ID"+Mail_id);
DA=BP*0.97;
HRA=BP*0.10;
PF=BP*0.12;
CF=BP*0.01;
GP=BP+DA+HRA;
NP=GP-PF-CF;
System.out.println("Basic Pay :"+BP);
System.out.println("Dearness Allowance : "+DA);
System.out.println("House Rent Allowance :"+HRA);
System.out.println("Provident Fund :"+PF);
System.out.println("Club Fund :"+CF);
22
System.out.println("Enter Basic pay of the Assistant Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Assistant ProfessorPay
Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class AssociateProfessor extends Employee
{
AssociateProfessor()
{
System.out.println("Enter Basic pay of the Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Associate
Professor Pay Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class Professor extends Employee
{
Professor()
{
System.out.println("Enter Basic pay of the Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Professor Pay
Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class Payslip
{
public static void main(String[] args)
{
char ans;
Scanner sc = new Scanner(System.in);
do
{
System.out.println("Main Menu");
System.out.println("1. Programmer \n2. Assistant Professor \n3. Associate
Professor \n4. Professor");
System.out.println("Enter your choice: ");
23
int choice=sc.nextInt();
switch(choice)
{
case 1:
Programmer p=new Programmer();
p.display();
break;
case 2:
AssistantProfessorap=new AssistantProfessor();
ap.display();
break;
case 3:
AssociateProfessor asp=new AssociateProfessor();
asp.display();
break;
case 4:
Professor PR=new Professor();
PR.display();
break;
}
System.out.println("Do you want to go to Main Menu?(y/n): ");
ans=sc.next().charAt(0);
}while(ans=='y'||ans=='Y');
sc.close();
}
}
OUTPUT:
Main Menu
1. Programmer
2. Assistant Professor
3. Associate Professor
4. Professor
Enter your choice:
1
Enter Name of the Employee:
Raja
Enter Address of the Employee:
Chennai
Enter ID of the Employee:
12345
Enter Mobile Number:
9876543210
Enter E-Mail ID of the Employee :
[email protected]
Enter Basic pay of the Programmer:
24
56000
==============================
Programmar Pay Slip
==============================
RESULT:
Thus, the Java application to generate pay slip for different category of employees was
implementedusing inheritance and the program was executed successfully.
25
EX.NO.:4
DATE: ABSTRACT CLASS IMPLEMENTATION
AIM:
To write a Java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class.
ALGORITHM:
PROGRAM:
AbstractArea.java
import java.util.*;
abstract class Shape
{
inta,b;
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
System.out.println("\t\tCalculating Area of Rectangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter length: ");
a=input.nextInt();
System.out.print("\nEnter breadth: ");
26
b=input.nextInt();
int area=a*b;
System.out.println("Area of Rectangle: "+area);
}
}
class Triangle extends Shape
{
void printArea()
{
System.out.println("\t\tCalculating Area of Triangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter height: ");
a=input.nextInt();
System.out.println("\nEnter breadth: ");
b=input.nextInt();
double area=0.5*a*b;
System.out.println("Area of Triangle: "+area);
}
}
class Circle extends Shape
{
void printArea()
{
System.out.println("\t\tCalculating Area of Circle");
Scanner input=new Scanner(System.in);
System.out.print("Enter radius: ");
a=input.nextInt();
double area=3.14*a*a;
System.out.println("Area of Circle: "+area);
}
}
class AbstractArea
{
public static void main(String[] args)
{
Shape obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
}
27
OUTPUT:
Calculating Area of Rectangle
Enter length: 10
Enter breadth: 20
Area of Rectangle: 200
Calculating Area of Triangle
Enter height: 34
Enter breadth: 56
Area of Triangle: 952.0
Calculating Area of Circle
Enter radius: 23
Area of Circle: 1661.06
RESULT:
Thus,the Java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class wasdeveloped and executed successfully.
28
EX.NO.: 5
DATE: INTERFACE
AIM:
To write a Java program to calculate the area of rectangle, circle and triangle by
implementing the interface shape.
ALGORITHM:
PROGRAM:
TestArea.java
import java.util.Scanner;
interface Shape
{
public void printArea();
}
class Rectangle implements Shape
{
public void printArea()
{
System.out.println("\t\tCalculating Area of Rectangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter length: ");
int a=input.nextInt();
System.out.print("\nEnter breadth: ");
int b=input.nextInt();
int area=a*b;
System.out.println("Area of Rectangle: "+area);
}
}
class Triangle implements Shape
{
public void printArea()
29
{
System.out.println("\t\tCalculating Area of Triangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter height: ");
int a=input.nextInt();
System.out.print("\nEnter breadth: ");
int b=input.nextInt();
double area=0.5*a*b;
System.out.println("Area of Triangle: "+area);
}
}
class Circle implements Shape
{
public void printArea()
{
System.out.println("\t\tCalculating Area of Circle");
Scanner input=new Scanner(System.in);
System.out.print("Enter radius: ");
int a=input.nextInt();
double area=3.14*a*a;
System.out.println("Area of Circle: "+area);
}
}
public class TestArea
{
public static void main(String[] args)
{
Shape obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
}
30
OUTPUT:
D:\Java\CS3381>javac TestArea.java
D:\Java\CS3381>java TestArea
Calculating Area of Rectangle
Enter length: 14
Enter breadth: 24
Area of Rectangle: 336
Calculating Area of Triangle
Enter height: 45
Enter breadth: 32
Area of Triangle: 720.0
Calculating Area of Circle
Enter radius: 5
Area of Circle: 78.5
D:\Java\CS3381>
RESULT:
Thus, the Java program to calculate the area of rectangle, circle and triangle using the
concept of interfacewasdeveloped and executed successfully.
31
EX.NO.:6
DATE: USER DEFINED EXCEPTION HANDLING
AIM:
To write a Java program to implement user defined exception handling.
ALGORITHM:
PROGRAM:
UserDefinedException.java
import java.util.*;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
32
class BankAccount
{
private double balance;
private intaccountNumber;
public BankAccount(intaccountNumber,doubleinitialBalance)throws
NegativeAmtException
{
if(initialBalance<0)
throw new NegativeAmtException("Initial amount should not be
negative!");
balance = initialBalance;
this.accountNumber = accountNumber;
}
public void deposit(double amount)throws NegativeAmtException
{
if (amount < 0)
{
throw new NegativeAmtException("Don't deposit negative amount!");
}
balance = balance + amount;
System.out.println("Amount deposited");
System.out.println("Balance amount : "+getBalance());
}
public void withdraw(double amount)throws NegativeAmtException
{
if (amount < 0)
{
throw new NegativeAmtException("Don't withdraw a negative
amount!");
}
else if(amount<=balance)
{
balance = balance – amount;
}
else
{
System.out.println("Insufficient amount");
}
System.out.println("Balance amount : "+getBalance());
}
public double getBalance()
{
return balance;
}
public intgetAccountNumber()
{
return accountNumber;
}
public String toString ()
{
33
return "Account Number :" + accountNumber + " Balance :" + balance;
}
}
public class UserDefinedException
{
public static void main(String[] args)
{
intch,amt;
Scanner sc=new Scanner(System.in);
System.out.print("Enter Account Number:");
int a=sc.nextInt();
System.out.print("Enter the initial Amount:");
int b=sc.nextInt();
BankAccount ac;
try
{
ac=new BankAccount(a,b);
while(true)
{
System.out.println("Main Menu");
System.out.println("1.Deposit \n2.Withdraw \n3.Check Balance
\n4.Display \n5.Exit");
System.out.print("Enter your Choice: ");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.print("Enter the amount to deposit:");
amt=sc.nextInt();
ac.deposit(amt);
break;
case 2:
System.out.print("Enter the amount to
Withdraw:");
amt=sc.nextInt();
ac.withdraw(amt);
break;
case 3:
System.out.println("Balance amount :
"+ac.getBalance());
break;
case 4:
System.out.println("Your account
details\n"+ac);
break;
case 5:
sc.close();
System.exit(0);
default:
34
System.out.println("Invalid Choice");
}
}
}
catch(NegativeAmtException e)
{
System.out.println("Exception Caught : "+e);
}
}
}
OUTPUT:
Enter Account Number:1234
Enter the initial Amount:500
Main Menu
1.Deposit
2.Withdraw
3.Check Balance
4.Display
5.Exit
Enter your Choice: 1
Enter the amount to deposit:-456
Exception Caught : Don't deposit negative amount!
RESULT:
Thus the Java program to implement user defined exception handling was implementedand
executed successfully.
35
EX.NO.: 7
DATE: MULTITHREADING IMPLEMENTATION
AIM:
To write a java program to implement a multi-threaded application.
ALGORITHM:
PROGRAM:
MultiThread.java
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: "
+ x * x);
}
}
class odd implements Runnable
{
public int x;
36
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " +
x * x * x);
}
}
class A extends Thread
{
public void run()
{
intnum = 0;
Random r = new Random();
try
{
for (inti = 0; i< 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " +
num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public classMultiThread
37
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
OUTPUT:
Main Thread and Generated Number is 33
New Thread 33 is ODD and Cube of 33 is: 35937
--------------------------------------
Main Thread and Generated Number is 31
New Thread 31 is ODD and Cube of 31 is: 29791
--------------------------------------
Main Thread and Generated Number is 25
New Thread 25 is ODD and Cube of 25 is: 15625
--------------------------------------
Main Thread and Generated Number is 43
New Thread 43 is ODD and Cube of 43 is: 79507
--------------------------------------
Main Thread and Generated Number is 14
New Thread 14 is EVEN and Square of 14 is: 196
--------------------------------------
RESULT:
Thus, the java program to implement multithreaded application was executed successfully.
38
EX.NO.: 8
DATE: FILE OPERATIONS
AIM:
To write a java program to copy the contents of one file to another file using file operations.
ALGORITHM:
PROGRAM:
FileCopy.java
import java.io.*;
class CopyFile
{
public static void main(String args[]) throws IOException
{
inti;
FileInputStream fin = null;
FileOutputStreamfout = null;
if(args.length != 2)
{
System.out.println("Usage: CopyFile from to");
return;
}
System.out.println("Displaying contents of "+ args[0]+"\n");
try
{
fin = new FileInputStream(args[0]);
do
39
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("Error Reading File");
}
finally
{
try
{
fin.close();
}
catch(IOException e)
{
System.out.println("Error Closing File");
}
}
System.out.println("\nCopying contents of "+ args[0] + "to " + args[1]+"\n");
try
{
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do
{
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("I/O Error: " + e);
}
finally
{
try
{
if(fin != null)
fin.close();
}
catch(IOException e2)
40
{
System.out.println("Error Closing Input File");
}
try
{
if(fout != null)
fout.close();
}
catch(IOException e2)
{
System.out.println("Error Closing Output File");
}
}
System.out.println("\nFile Copied\n");
System.out.println("\nDisplaying contents of "+ args[1]+"\n");
try
{
fin = new FileInputStream(args[1]);
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("Error Reading File");
}
finally
{
try
{
fin.close();
}
catch(IOException e)
{
System.out.println("Error Closing File");
}
}
}
}
41
OUTPUT:
R:\oop>javac CopyFile.java
R:\oop>java CopyFile FIRST.txt SECOND.txt
File Copied
R:\oop>
RESULT:
Thus, the java program to copy the contents of one file to another file using file was written,
executed and verified.
42
EX.NO.: 10
DATE: GENERIC CLASS
AIM:
To write a java program to find the maximum and minimum value from the given type of
elements using ageneric function.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class Myclass to implement generic class and generic methods.
Step 3: Get the set of the values belonging to specific data type.
Step 4:Create the objects of the class to hold integer, character and double values.
Step 5:Create the method to compare the values and find the maximum value stored in the
array.
Step 6: Invoke the method with integer, character, double and string values. The output will
be displayedbased on the data type passed to the method.
Step 7:Stop the program.
PROGRAM:
GenericsDemo.java
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] obj)
{
vals = obj;
}
public T min()
{
T v = vals[0];
for(inti=1; i<vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(inti=1; i<vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
43
return v;
}
}
class GenericsDemo
{
public static void main(String args[])
{
Integer num[]={10,2,5,4,6,1};
Character ch[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
String str[]= {"hai","how","are","you"};
MyClass<Integer>iob = new MyClass<Integer>(num);
MyClass<Character> cob = new MyClass<Character>(ch);
MyClass<Double>dob = new MyClass<Double>(d);
MyClass<String>sob=new MyClass<String>(str);
System.out.println("Max value in num: " + iob.max());
System.out.println("Min value in num: " + iob.min());
System.out.println("Max value in ch: " + cob.max());
System.out.println("Min value in ch: " + cob.min());
System.out.println("Max value in d: " + dob.max());
System.out.println("Min value in d: " + dob.min());
System.out.println("Max value in str: " + sob.max());
System.out.println("Min value in str: " + sob.min());
}
}
OUTPUT:
Max value in num: 10
Min value in num: 1
Max value in ch: v
Min value in ch: a
Max value in d: 88.3
Min value in d: 10.4
Max value in str: you
Min value in str: are
RESULT:
Thus, the Java program to find the maximum and minimum value from the given type of
elements was implemented using generics and executed successfully.
44
EX.NO.: 10(a)
DATE: MULTIPLE CHOICE TEST QUESTION IN JAVAFX
AIM:
To write a program to display multiple choice test question using JavaFX.
ALGORITHM:
PROGRAM:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MCTest extends Application
{
@Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("Test Question 1");
Label labelfirst= new Label("What is 10 + 20?");
Label labelresponse= new Label();
Button button= new Button("Submit");
RadioButton radio1, radio2, radio3, radio4;
radio1=new RadioButton("10");
45
radio2= new RadioButton("20");
radio3= new RadioButton("30");
radio4= new RadioButton("40");
button.setDisable(true);
radio1.setOnAction(e ->button.setDisable(false) );
radio2.setOnAction(e ->button.setDisable(false) );
radio3.setOnAction(e ->button.setDisable(false) );
radio4.setOnAction(e ->button.setDisable(false) );
button.setOnAction(e ->
{
if (radio3.isSelected())
{
labelresponse.setText("Correct answer");
button.setDisable(true);
}
else
{
labelresponse.setText("Wrong answer");
button.setDisable(true);
}
});
VBox layout= new VBox(5);
layout.getChildren().addAll(labelfirst, radio1, radio2, radio3, radio4, button,
labelresponse);
Scene scene1= new Scene(layout, 400, 250);
primaryStage.setScene(scene1);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
46
OUTPUT:
RESULT:
Thus, the Java program for multiple choice test questions was implemented and executed
successfully.
47
EX.NO.: 10(b)
DATE: SIMPLE EDITOR USING JAVAFX
AIM:
To write a program to create simple editor with menu using JavaFX.
ALGORITHM:
PROGRAM:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
public class MenuUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception
{
48
Menu newmenu = new Menu("File");
Menu newmenu2 = new Menu("Edit");
MenuItem m1 = new MenuItem("Open");
MenuItem m2 = new MenuItem("Save");
MenuItem m3 = new MenuItem("Exit");
MenuItem m4 = new MenuItem("Cut");
MenuItem m5 = new MenuItem("Copy");
MenuItem m6 = new MenuItem("Paste");
newmenu.getItems().add(m1);
newmenu.getItems().add(m2);
newmenu.getItems().add(m3);
newmenu2.getItems().add(m4);
newmenu2.getItems().add(m5);
newmenu2.getItems().add(m6);
MenuBar newmb = new MenuBar();
newmb.getMenus().add(newmenu);
newmb.getMenus().add(newmenu2);
Label l = new Label("\t\t\t\t\t\t + "You have selected no menu items");
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
l.setText("\t\t\t\t\t\t" + ((MenuItem)e.getSource()).getText() +
" menu item selected");
}
};
m1.setOnAction(event);
m2.setOnAction(event);
m3.setOnAction(event);
m4.setOnAction(event);
m5.setOnAction(event);
m6.setOnAction(event);
VBox box = new VBox(newmb,l);
Scene scene = new Scene(box,400,200);
primaryStage.setScene(scene);
49
primaryStage.setTitle("JavaFX Menu");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
OUTPUT:
RESULT:
Thus, the Java program for simple editor was implemented and executed successfully.
50
EX.NO.: 11
DATE: MINI PROJECT(LIBRARY MANAGEMENT SYSTEM)
Aim:
To create a library management system using java program.
Procedure:
The Library Management System has become an essential tool for public libraries, school libraries,
college libraries. The Library management system helps librarians to manage, maintain and monitor
the library.
There will be two module:
1. Librarian
2. User/Student
Functions of Librarian:
Librarians can add users.
Librarians can add books.
Librarians can issue books for users.
Librarians can make entries of the return books of the users.
Librarians can view users.
Librarians can view books.
Librarians can view issued books.
Librarians can view returned books.
Functions of Student/User:
Users can check or view available books of the library
Users can check or view his/her issued books.
Users can check or view his/her returned books status.
Project Prerequisites:
1. Creating Database
2. Importing packages
3. Functions used
4. Connection to database
5. Defining Login function
6. Defining Librarian functions
51
7. Defining Student function
1. Create Database
Users table for storing information such as username, password, user_type and users table is
used for login purposes.
Books table for storing books details of library.
Issued books table for storing the entries of the user if he/she took a book from the library.
Return books table for storing the entries of the user if he/she returns the books to the library.
Sql Queries
a) Creating database:
52
`ISSUED_DATE` varchar(20) NOT NULL,
)
f) Inserting user:
53
INSERT INTO USERS(USERNAME,PASSWORD,USER_TYPE) VALUES (“admin”,”admin”,1)
2. Importing packages
In this step, we will import required packages such as swing, awt, jxdatepicker library, mysql-
connector library. etc. By default, Swing & AWT packages are installed by JAVA.
But, jxdatepicker library and MySQL-connector library we have to download and import into our
library management system project.
Click on Tools >> Libraries >> At bottom left Click on “New Library”. Now, name your library
and click on “OK”:
Click on Add JAR/Folder and select the downloaded file to add in our project. Now, add that
library to java library management project.
54
Code:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.JXDatePicker;
3. Functions used
setLayout(layout): This function will define the layout of the frame, window, pane, in which
all the components are arranged.
setText(“your text”): This function will set the title or the text on the label, button, etc.
setVisible(true): This function will make the frame or window visible to the user. By default,
it is false.
setSize(int width, int height): This function takes two parameters such as height and width. It
is used to define the size of frame/window, panel, etc.
setBackground(new Color(255,255,255)): This function will set the background color of the
UI component.
setForeground(new Color(255,255,255)): This function will set the foreground color of the
UI component.
add(obj): This function is used to add the components in a sequential manner to the frame or
panel.
executeQuery(string query): This function will execute the sql query.
next(): This function will move the cursor to a new row of the table.
showMessageDialog(): This function will enable the dialog box to show the message on the
top of the frame.
getText(): This function will get the text from the textfield input of the user.
parseInt(“text”): This function will convert the string into the integer data type.
setResizable(false): This function sets the frame/window resizable. By default, it is true.
55
setColumnIdentifiers(String names): This function will set the column names of the model of
the table.
setOpaque(true): This function will set up opaque so that the label component paints every
pixel within its bounds.
addRow(Object): This function will add the data to the new row of the model of the table.
isSelected(): This function will return true if the radio button is selected otherwise it will
return false.
dispose(): This function will close the frame / window of library management system.
getString(int column): This function will get the varchar/string data from the table of the
mysql database.
getInt(int column): This function will get the integer data from the table of the mysql
database.
4. Connection to database
In this step, we will create a connection method as a reusable component, this method will connect
the library management to mysql database. Make sure that you enter the proper url string of
database connection such as port number, username, password, etc.
Function definitions:
forName(driverClassName): This function is used to register with the driver of the database.
getConnection(url): This function is used to make connections with databases. It takes parameters
such as hostname, port number, database, username, password, etc. Generalized form:
“jdbc:mysql://hostname:port/dbName”, “username”, “password”. If your mysql does not have a
password then enter “” as an empty string.
Code:
public static Connection connect() {
//Making Database Connection once & using multiple times whenever required.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/
return con;
ex.printStackTrace();
return null;
56
5. Defining Login function
In this step, we will define a login method, which will authenticate the user to java library
management system. If the user type is admin then it is redirected to the librarian functions
dashboard else user functions dashboard is redirected. This method will take 2 parameters such as
username and password. If the user enters an empty string then it will give a message to the user to
enter the correct details.
Login Code:
//Setting up opaque so that label component paints every pixel within its bounds.
l1.setOpaque(true);
l1.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l2.setOpaque(true);
l2.setForeground(Color.white);
57
//Setting up the foreground color of the textfield.
usernameTF.setForeground(Color.white);
passwordTF.setForeground(Color.white);
loginBtn.setForeground(Color.white);
cancelBtn.setForeground(Color.white);
loginBtn.addActionListener(new ActionListener() {
@Override
if (username.isEmpty()) {
58
JOptionPane.showMessageDialog(null, "Please enter username"); //Display dialog box with the
message
else if (password.isEmpty()) {
} //If both the fields are present then to login the user, check whether the user exists already
else {
try {
} else {
loginFrame.dispose();
while (rs.next()) {
System.out.println(admin);
librarian_frame();
} else {
user_frame(UID);
59
}
ex.printStackTrace();
});
cancelBtn.addActionListener(new ActionListener() {
@Override
loginFrame.dispose();
});
//Adding all login components in the login frame of java library management system.
loginFrame.add(l1);
loginFrame.add(usernameTF);
loginFrame.add(l2);
loginFrame.add(passwordTF);
loginFrame.add(loginBtn);
loginFrame.add(cancelBtn);
loginFrame.setVisible(true);
60
loginFrame.setResizable(false);
}
6. Defining Librarian functions
In this step, we will create the dashboard of the librarian, in which we will have 8 buttons such as
add user, add book, issue book, return book, view users, view books, view issued books, view
returned books. Each button will have its own action listeners to perform its own task.
Dashboard Functions:
1. Add user: The librarian will enter the details such as username, password, user type of the user
and user will be added.
2. Add books: The librarian will enter the details of the new book such as isbn, book name, book
publisher, price, pages, edition, etc. The details will be entered into the database and the book
will be added.
3. Issue book: The librarian will enter the details of the issue book of the user such as book id,
user id, date at which book was issued, etc. The details will be entered into the database and
the book will be issued.
4. Return book: The librarian will enter the details of the return book of the user such as book id,
user id, date at which book was returned, fine(if any), etc. The details will be entered into the
java library management system.
5. View users: The librarian can view details of the users anytime.
6. View books: The librarian can view details of the books of the library anytime.
7. View issued books: The librarian can view details of the issued books anytime.
8. View returned books: The librarian can view details of the returned books anytime.
Code:
public static void librarian_frame() {
//Creating Button
view_books_btn.setForeground(Color.white);
61
view_books_btn.addActionListener(new ActionListener() {
@Override
//Creating frame.
//Connection to Database
try {
//Creating Statement
//Executing query
ResultSet rs = stmt.executeQuery(sql);
String[] bookColumnNames = {"Book ID", "Book ISBN", "Book Name", "Book Publisher", "Book
Edition", "Book Genre", "Book price", "Book Pages"};
bookModel.setColumnIdentifiers(bookColumnNames);
book_list.setModel(bookModel);
book_list.setForeground(Color.white);
62
book_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
book_list.setFillsViewportHeight(true);
book_list.setFocusable(false);
scrollBook.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEED
ED);
scrollBook.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
while (rs.next()) {
viewBooksFrame.add(scrollBook);
viewBooksFrame.setSize(800, 400);
viewBooksFrame.setVisible(true);
63
//Creating Dialog box to show any error if occured!
JOptionPane.showMessageDialog(null, e1);
});
//Creating button
view_users_btn.setForeground(Color.white);
view_users_btn.addActionListener(new ActionListener() {
@Override
//Creating frame.
//Connection to database
try {
//Creating Statement
//Executing query
ResultSet rs = stmt.executeQuery(sql);
64
//Creating model for the table
userModel.setColumnIdentifiers(userColumnNames);
users_list.setModel(userModel);
users_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
users_list.setFillsViewportHeight(true);
users_list.setForeground(Color.white);
scrollUser.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDE
D);
scrollUser.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
while (rs.next()) {
if (user_type == 1) {
} else {
65
}
viewUsersFrame.add(scrollUser);
viewUsersFrame.setSize(800, 400);
viewUsersFrame.setVisible(true);
JOptionPane.showMessageDialog(null, e1);
});
//Creating button
view_issued_books_btn.setForeground(Color.white);
view_issued_books_btn.addActionListener(new ActionListener() {
@Override
//Creating button
//Connection to database
66
String sql = "select * from issued_books";
try {
//Creating Statement
//Executing query
ResultSet rs = stmt.executeQuery(sql);
String[] issueBookColumnNames = {"Issue ID", "User ID", "Book ID", "Issue Date", "Period"};
issuedBookModel.setColumnIdentifiers(issueBookColumnNames);
issue_book_list.setModel(issuedBookModel);
issue_book_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
issue_book_list.setFillsViewportHeight(true);
issue_book_list.setFocusable(false);
issue_book_list.setForeground(Color.white);
scrollIssuedBook.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_
NEEDED);
scrollIssuedBook.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEED
ED);
67
while (rs.next()) {
issuedBooksFrame.add(scrollIssuedBook);
issuedBooksFrame.setSize(800, 400);
issuedBooksFrame.setVisible(true);
JOptionPane.showMessageDialog(null, e1);
});
//Creating button
view_returned_books_btn.setForeground(Color.white);
68
view_returned_books_btn.addActionListener(new ActionListener() {
@Override
//Creating button.
try {
//Creating Statement.
//Executing query.
ResultSet rs = stmt.executeQuery(sql);
String[] returnBookColumnNames = {"Return ID", "Book ID", "User ID", "Return Date", "Fine"};
returnBookModel.setColumnIdentifiers(returnBookColumnNames);
returned_book_list.setModel(returnBookModel);
returned_book_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
returned_book_list.setFillsViewportHeight(true);
returned_book_list.setFocusable(false);
69
//Setting the foreground colour of the table.
returned_book_list.setForeground(Color.white);
scrollReturnedBook.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS
_NEEDED);
scrollReturnedBook.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEE
DED);
while (rs.next()) {
returnedBooksFrame.add(scrollReturnedBook);
returnedBooksFrame.setSize(800, 400);
returnedBooksFrame.setVisible(true);
JOptionPane.showMessageDialog(null, e1);
70
});
//Creating button
add_user_btn.setForeground(Color.white);
add_user_btn.addActionListener(new ActionListener() {
@Override
//Creating frame
JFrame add_user_frame = new JFrame("Enter User Details"); //Frame to enter user details
//Creating label
//Setting up opaque so that label component paints every pixel within its bounds.
l1.setOpaque(true);
l1.setForeground(Color.white);
//Creating label
//Setting up opaque so that label component paints every pixel within its bounds.
l2.setOpaque(true);
l2.setForeground(Color.white);
71
//Creating textfield
add_username_tf.setForeground(Color.white);
//Creating textfield
add_password_tf.setForeground(Color.white);
//Aligning center
user_type_radio1.setHorizontalAlignment(SwingConstants.CENTER);
user_type_radio1.setForeground(Color.white);
//Aligning center
user_type_radio2.setHorizontalAlignment(SwingConstants.CENTER);
user_type_radio2.setForeground(Color.white);
72
ButtonGroup user_type_btn_grp = new ButtonGroup();
user_type_btn_grp.add(user_type_radio1);
user_type_btn_grp.add(user_type_radio2);
//Creating button.
create_btn.setForeground(Color.white);
//Creating button.
user_entry_cancel_btn.setForeground(Color.white);
create_btn.addActionListener(new ActionListener() {
@Override
//Connection to database.
try {
//Creating statement
73
if (user_type_radio1.isSelected()) {
add_user_frame.dispose();
} else {
add_user_frame.dispose();
JOptionPane.showMessageDialog(null, e1);
});
user_entry_cancel_btn.addActionListener(new ActionListener() {
@Override
add_user_frame.dispose();
});
74
add_user_frame.add(l1);
add_user_frame.add(add_username_tf);
add_user_frame.add(l2);
add_user_frame.add(add_password_tf);
add_user_frame.add(user_type_radio1);
add_user_frame.add(user_type_radio2);
add_user_frame.add(create_btn);
add_user_frame.add(user_entry_cancel_btn);
add_user_frame.setSize(350, 200);
add_user_frame.setVisible(true);
add_user_frame.setResizable(false);
});
//Creating button.
add_book_btn.setForeground(Color.white);
add_book_btn.addActionListener(new ActionListener() {
@Override
//Creating Frame.
75
JFrame book_frame = new JFrame("Enter Book Details");
//Creating labels
//Setting up opaque so that label component paints every pixel within its bounds.
l1.setOpaque(true);
l1.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l2.setOpaque(true);
l2.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l3.setOpaque(true);
l3.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l4.setOpaque(true);
76
//Setting the foreground colour of the label.
l4.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l5.setOpaque(true);
l5.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l6.setOpaque(true);
l6.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l7.setOpaque(true);
l7.setForeground(Color.white);
//Creating textfield.
book_isbn_tf.setForeground(Color.white);
77
//Creating textfield
book_name_tf.setForeground(Color.white);
//Creating textfield.
book_publisher_tf.setForeground(Color.white);
//Creating textfield.
book_edition_tf.setForeground(Color.white);
//Creating textfield.
book_genre_tf.setForeground(Color.white);
//Creating textfield.
78
book_price_tf.setForeground(Color.white);
//Creating textfield.
book_pages_tf.setForeground(Color.white);
//Creating button.
create_btn.setForeground(Color.white);
//Creating button.
add_book_cancel_btn.setForeground(Color.white);
create_btn.addActionListener(new ActionListener() {
@Override
79
//Converting bookprice and bookpages to integer from string.
//Connection to database.
try {
//Creating statement
stmt.executeUpdate("INSERT INTO
BOOKS(book_isbn,book_name,book_publisher,book_edition,book_genre,book_price,book_pages)
"
+ " VALUES ('" + book_isbn + "','" + book_name + "','" + book_publisher + "','" + book_edition +
"','" + book_genre + "','" + book_price + "'," + book_pages + ")");
book_frame.dispose();
JOptionPane.showMessageDialog(null, e1);
});
add_book_cancel_btn.addActionListener(new ActionListener() {
@Override
book_frame.dispose();
});
80
//Adding components in the frame.
book_frame.add(l1);
book_frame.add(book_isbn_tf);
book_frame.add(l2);
book_frame.add(book_name_tf);
book_frame.add(l3);
book_frame.add(book_publisher_tf);
book_frame.add(l4);
book_frame.add(book_edition_tf);
book_frame.add(l5);
book_frame.add(book_genre_tf);
book_frame.add(l6);
book_frame.add(book_price_tf);
book_frame.add(l7);
book_frame.add(book_pages_tf);
book_frame.add(create_btn);
book_frame.add(add_book_cancel_btn);
book_frame.setSize(800, 500);
book_frame.setVisible(true);
book_frame.setResizable(false);
});
//Creating button
81
//Setting background colour of the button.
add_issue_book_btn.setForeground(Color.white);
add_issue_book_btn.addActionListener(new ActionListener() {
@Override
//Creating frame.
//Creating panel.
//Creating a datepicker.
picker.setDate(Calendar.getInstance().getTime());
//Formatting datepicker.
picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));
pickerPanel.add(picker);
pickerPanel.setForeground(Color.white);
//Creating labels
//Setting up opaque so that label component paints every pixel within its bounds.
l1.setOpaque(true);
82
//Setting background colour of the label.
l1.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l2.setOpaque(true);
l2.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l3.setOpaque(true);
l3.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l4.setOpaque(true);
l4.setForeground(Color.white);
//Creating textfield.
83
//Setting the foreground colour of the textfield.
bid_tf.setForeground(Color.white);
//Creating textfield.
uid_tf.setForeground(Color.white);
//Creating textfield.
period_tf.setForeground(Color.white);
//Creating button.
create_btn.setForeground(Color.white);
//Creating button.
issue_book_cancel_btn.setForeground(Color.white);
create_btn.addActionListener(new ActionListener() {
@Override
84
public void actionPerformed(ActionEvent e) {
//Formatting date.
try {
//Creating Statement
issue_book_frame.dispose();
JOptionPane.showMessageDialog(null, e1);
});
issue_book_cancel_btn.addActionListener(new ActionListener() {
85
@Override
issue_book_frame.dispose();
});
issue_book_frame.add(l1);
issue_book_frame.add(bid_tf);
issue_book_frame.add(l2);
issue_book_frame.add(uid_tf);
issue_book_frame.add(l3);
issue_book_frame.add(period_tf);
issue_book_frame.add(l4);
issue_book_frame.getContentPane().add(pickerPanel);
issue_book_frame.add(create_btn);
issue_book_frame.add(issue_book_cancel_btn);
issue_book_frame.setSize(600, 300);
issue_book_frame.setVisible(true);
issue_book_frame.setResizable(false);
});
//Creating button.
86
add_return_book_btn.setBackground(new Color(51, 35, 85));
add_return_book_btn.setForeground(Color.white);
add_return_book_btn.addActionListener(new ActionListener() {
@Override
//Creating frame.
//Setting up opaque so that label component paints every pixel within its bounds.
l1.setOpaque(true);
l1.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l2.setOpaque(true);
l2.setForeground(Color.white);
//Creating labels.
//Setting up opaque so that label component paints every pixel within its bounds.
l3.setOpaque(true);
87
l3.setBackground(new Color(51, 35, 85));
l3.setForeground(Color.white);
//Setting up opaque so that label component paints every pixel within its bounds.
l4.setOpaque(true);
l4.setForeground(Color.white);
//Creating textfield.
bid_tf.setForeground(Color.white);
//Creating textfield.
uid_tf.setForeground(Color.white);
//Creating a datepicker.
picker.setDate(Calendar.getInstance().getTime());
88
picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));
//Creating textfield.
fine_tf.setForeground(Color.white);
pickerPanel.add(picker);
pickerPanel.setForeground(Color.white);
//Creating button.
return_book_btn.setForeground(Color.white);
//Creating button.
cancel_book_btn.setForeground(Color.white);
return_book_btn.addActionListener(new ActionListener() {
@Override
89
//Getting data from text fields.
//Formatting Date.
try {
//Connection to database
//Creating Statement
returnBookFrame.dispose();
JOptionPane.showMessageDialog(null, e1);
});
cancel_book_btn.addActionListener(new ActionListener() {
@Override
90
returnBookFrame.dispose();
});
returnBookFrame.add(l1);
returnBookFrame.add(bid_tf);
returnBookFrame.add(l2);
returnBookFrame.add(uid_tf);
returnBookFrame.add(l3);
returnBookFrame.getContentPane().add(pickerPanel);
returnBookFrame.add(l4);
returnBookFrame.add(fine_tf);
returnBookFrame.add(return_book_btn);
returnBookFrame.add(cancel_book_btn);
returnBookFrame.setSize(600, 300);
returnBookFrame.setVisible(true);
returnBookFrame.setResizable(false);
});
librarianFrame.add(add_user_btn);
librarianFrame.add(add_book_btn);
91
librarianFrame.add(add_issue_book_btn);
librarianFrame.add(add_return_book_btn);
librarianFrame.add(view_users_btn);
librarianFrame.add(view_books_btn);
librarianFrame.add(view_issued_books_btn);
librarianFrame.add(view_returned_books_btn);
librarianFrame.setSize(800, 200);
librarianFrame.setVisible(true);
librarianFrame.setResizable(false);
}
7. Defining Student functions
In this step, we will create the dashboard of the student/user, in which we will have 3 buttons such
as view books, view issued books, view returned books. Each button will have its own action
listeners to perform its own task.
Dashboard Functions:
1. View books: The student can view details of the books of the library anytime.
2. View issued books: The student can check and view which books he/she has issued in the java
library management system.
3. View returned books: The student can check and view which books he/she has returned to the
library.
Code:
public static void user_frame(String UID) {
//Creating button
92
view_books_btn.setForeground(Color.white);
view_books_btn.addActionListener(new ActionListener() {
@Override
//Creating Frame.
//Connection to database.
try {
//Creating Statement.
//Executing query.
ResultSet rs = stmt.executeQuery(sql);
String[] bookColumnNames = {"Book ID", "Book ISBN", "Book Name", "Book Publisher", "Book
Edition", "Book Genre", "Book price", "Book Pages"};
bookModel.setColumnIdentifiers(bookColumnNames);
book_list.setModel(bookModel);
book_list.setForeground(Color.white);
93
//Setting up the table auto-resizable.
book_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
book_list.setFillsViewportHeight(true);
book_list.setFocusable(false);
scrollBook.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEED
ED);
scrollBook.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
while (rs.next()) {
viewBooksUserFrame.add(scrollBook);
viewBooksUserFrame.setSize(800, 400);
viewBooksUserFrame.setVisible(true);
94
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1);
);
//Creating Button.
view_user_issued_books_btn.setForeground(Color.white);
view_user_issued_books_btn.addActionListener(new ActionListener() {
@Override
//Creating frame
//Storing userid
//Connection to database
//Database Query
95
+ " books.book_pages as book_pages, issued_books.issued_date as issued_date,
issued_books.period as period from books,"
try {
//Creating statement
//Executing query
ResultSet rs = stmt.executeQuery(sql);
String[] issuedBookColumnNames = {"Issue ID", "Book ID", "User ID", "Book ISBN", "Book
Name", "Book Publisher", "Book Edition", "Book Genre", "Book Price", "Book Pages", "Issued
Date", "Period"};
bookModel.setColumnIdentifiers(issuedBookColumnNames);
issued_book_list.setModel(bookModel);
issued_book_list.setForeground(Color.white);
issued_book_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
issued_book_list.setFillsViewportHeight(true);
issued_book_list.setFocusable(false);
96
scrollIssuedBook.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_
NEEDED);
scrollIssuedBook.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEED
ED);
while (rs.next()) {
//Adding scrollbars.
viewUserIssuedBooksFrame.add(scrollIssuedBook);
viewUserIssuedBooksFrame.setSize(1200, 600);
viewUserIssuedBooksFrame.setVisible(true);
viewUserIssuedBooksFrame.setResizable(false);
97
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1);
});
//Creating Button
view_user_returned_books_btn.setForeground(Color.white);
view_user_returned_books_btn.addActionListener(new ActionListener() {
@Override
//Creating frame
//Storing userid
//Connection to database
98
+ "books.book_pages as book_pages, returned_books.return_date as return_date,
returned_books.fine as fine "
try {
//Creating Statement
//Executing query
ResultSet rs = stmt.executeQuery(sql);
String[] returnedBookColumnNames = {"Return ID", "Book ID", "User ID", "Book ISBN", "Book
Name", "Book Publisher", "Book Edition", "Book Genre", "Book Price", "Book Pages", "Returned
Date", "Fine"};
bookModel.setColumnIdentifiers(returnedBookColumnNames);
returned_book_list.setModel(bookModel);
returned_book_list.setForeground(Color.white);
returned_book_list.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
returned_book_list.setFillsViewportHeight(true);
returned_book_list.setFocusable(false);
99
scrollIssuedBook.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_
NEEDED);
scrollIssuedBook.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEED
ED);
while (rs.next()) {
//Adding scrollbars.
viewUserReturnedBooksFrame.add(scrollIssuedBook);
viewUserReturnedBooksFrame.setSize(1200, 600);
viewUserReturnedBooksFrame.setVisible(true);
viewUserReturnedBooksFrame.setResizable(false);
100
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1);
});
studentFrame.add(view_books_btn);
studentFrame.add(view_user_issued_books_btn);
studentFrame.add(view_user_returned_books_btn);
studentFrame.setSize(500, 500);
studentFrame.setVisible(true);
studentFrame.setResizable(false);
}
Screen Shorts:
Login Page
101
Librarian Functions:
102
Conclusion:
We have finally built our Library Management System using Java and MySQL. Now librarians can
add users, books, issue books, return books, and also they can view users, books, issued books,
returned books. Students/Users can view available books of the library, also users can check which
book his/her issued books and returned books. From this java project, we have also learned how we
can connect a MySQL database with java, and also how to query a database via Java program.
103