0% found this document useful (0 votes)
23 views71 pages

Record Oop Cs3381

Uploaded by

Arockia Pravina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views71 pages

Record Oop Cs3381

Uploaded by

Arockia Pravina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

SOLVE PROBLEMS BY USING SEQUENTIAL SEARCH

EX.NO.:1(a)
DATE:

AIM:

ALGORITHM:
PROGRAM:
LinearSearch.java
public class LinearSearch
{
static int search(int arr[], int n, int s)
{
for (int i = 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);
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac LinearSearch.java
C:\jdk-21.0.2\bin>java LinearSearch Element found at index 1

RESULT:
SOLVE PROBLEMS BY USING BINARY SEARCH
EX.NO.:1(b)
DATE:

AIM:

ALGORITHM:
PROGRAM:
BinarySearch.java
class BinarySearch
{
public static int binarySearch(int arr[], 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);
}
}
return -1;
}
public static void main(String args[])
{
int arr[] = {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:
C:\jdk-21.0.2\bin>javac BinarySearch.java
C:\jdk-21.0.2\bin>java BinarySearch
Element is found at index: 2

RESULT:
SOLVE PROBLEMS BY USING QUADRATIC SORTING ALGORITHMS-
SELECTION SORT
EX.NO.:1(c)
DATE:

AIM:

ALGORITHM:
PROGRAM:
SelectionSort.java
public class SelectionSort
{
public static void selectionsort(int[] arr)
{
int n=arr.length;
for(int i=0;i<n-1;i++)
{
int min=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min])
{
min=j;
}
}
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:
C:\jdk-21.0.2\bin>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
C:\jdk-21.0.2\bin>

RESULT:
SOLVE PROBLEMS BY USING QUADRATIC SORTING ALGORITHMS-INSERTION
SORT
EX.NO.:1(d)
DATE:

AIM:

ALGORITHM:
PROGRAM:

InsertionSort.java

public class InsertionSort


{
public static void main(String args[])
{
int num[]= {12,9,37,86,2,17,5};
int i,j,x;
System.out.println("Array before Insertion Sort");
for(i=0; i<num.length; i++)
{
System.out.print(num[i]+" ");
}
for(i=1; i<num.length; i++)
{
x=num[i];
j=i-1;
while(j>=0)
{
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:
C:\jdk-21.0.2\bin>java InsertionSort
Array before Insertion Sort
12 9 37 86 2 17 5

Array after Insertion Sort


2 5 9 12 17 37 86

RESULT:
DEVELOP STACK DATA STRUCTURES USING CLASSES AND OBJECTS

EX.NO.: 2(a)

DATE:

AIM:

ALGORITHM:
PROGRAM:
Stack.java
import java.util.Scanner;
public class Stack
{
private int maxsize, top;
private int[] st;
public Stack(int size)
{
maxsize = size;
st = new int[maxsize];
top = -1;
}
boolean isEmpty()
{
return top==-1;
}
boolean isFull()
{
return top==maxsize-1;
}
public void push(int element)
{
if(isFull())
System.out.println("Overflow");
else
st[++top] = element;
}
public int pop()
{
if(isEmpty())
{
System.out.println("UnderFlow");
return (-1);
}
return (st[top--]);
}
public void printStack()
{
System.out.println("Stack Elements:");
for (int i = 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");
int ch = 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:

C:\jdk-21.0.2\bin>javac Stack.java

C:\jdk-21.0.2\bin>java Stack
Enter stack size
5

STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
1
Enter Element
5

STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
1
Enter Element
8

STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
5
Wrong option

STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
3
Stack Elements:
8
5

STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
2
Poped element is 8
STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice
3
Stack Elements:
5

STACK
*****
1.PUSH
2.POP
3.Display
4.EXIT
Enter your choice

RESULT:
DEVELOP QUEUE DATA STRUCTURES USING CLASSES AND OBJECTS

EX.NO.: 2(b)

DATE:

AIM:

ALGORITHM:
PROGRAM:
Queue.java
import java.util.Scanner;
public class Queue
{
private int items[];
private int maxsize, front, rear;
Queue(int size)
{
maxsize=size;
items = new int[size];
front = -1;
rear = -1;
}
boolean isFull()
{
if (front == 0 && rear ==maxsize-1) {
return true;
}
return false;
}
boolean isEmpty()
{
if (front == -1)
return true;
else
return false;
}
void enQueue(int element)
{
if (isFull())
{
System.out.println("Queue is full");
}
else
{
if (front == -1)
front = 0;
rear++;
items[rear] = element;
System.out.println("Inserted " + element); }
}
int deQueue()
{
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);
}
}
void display()
{
int i;
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");
int ch = sc.nextInt();
switch (ch)
{
case 1:
System.out.println("Enter Element");
int n = sc.nextInt();
obj.enQueue(n);
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:
C:\jdk-21.0.2\bin>javac Queue.java
C:\jdk-21.0.2\bin>java Queue
Enter queue size
5

QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
4
Inserted 4

QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
7
Inserted 7

QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
1
Enter Element
9
Inserted 9

QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
3

Front index-> 0
Items ->
479
Rear index-> 2

QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
2
Dequeued element is 4
QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
3

Front index-> 1
Items ->
79
Rear index-> 2

QUEUE
*****
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EXIT
Enter your choice
RESULT:
Develop a java application with an Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor
and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes
with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club funds.
Generate pay slips for the employees with their gross and net salary.

EX.NO.: 3
DATE:
AIM:

ALGORITHM:
PROGRAM:
EmployeeManagement.java
class EmployeeManagement {

// Base Employee class


static class Employee {
protected String empName;
protected String empId;
protected String address;
protected String mailId;
protected String mobileNo;
protected double basicPay;

// Constructor
public Employee(String empName, String empId, String address, String mailId, String
mobileNo, double basicPay) {
this.empName = empName;
this.empId = empId;
this.address = address;
this.mailId = mailId;
this.mobileNo = mobileNo;
this.basicPay = basicPay;
}

// Method to generate pay slip


public void generatePaySlip() {
double da = basicPay * 0.97;
double hra = basicPay * 0.10;
double pf = basicPay * 0.12;
double staffClubFunds = basicPay * 0.001;
double grossSalary = basicPay + da + hra;
double netSalary = grossSalary - pf - staffClubFunds;

System.out.println("Pay Slip for " + empName);


System.out.println("Employee ID: " + empId);
System.out.println("Address: " + address);
System.out.println("Mail ID: " + mailId);
System.out.println("Mobile No: " + mobileNo);
System.out.println("Basic Pay: " + basicPay);
System.out.println("Dearness Allowance (DA): " + da);
System.out.println("House Rent Allowance (HRA): " + hra);
System.out.println("Provident Fund (PF): " + pf);
System.out.println("Staff Club Funds: " + staffClubFunds);
System.out.println("Gross Salary: " + grossSalary);
System.out.println("Net Salary: " + netSalary);
System.out.println();
}
}

// Programmer class
static class Programmer extends Employee {
public Programmer(String empName, String empId, String address, String mailId, String
mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo, basicPay);
}
}

// Assistant Professor class


static class AssistantProfessor extends Employee {
public AssistantProfessor(String empName, String empId, String address, String mailId, String
mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo, basicPay);
}
}

// Associate Professor class


static class AssociateProfessor extends Employee {
public AssociateProfessor(String empName, String empId, String address, String mailId, String
mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo, basicPay);
}
}

// Professor class
static class Professor extends Employee {
public Professor(String empName, String empId, String address, String mailId, String mobileNo,
double basicPay) {
super(empName, empId, address, mailId, mobileNo, basicPay);
}
}

// Main method to test the implementation


public static void main(String[] args) {
// Create instances of different employees
Programmer programmer = new Programmer("Alice Johnson", "P001", "123 Main St",
"alice.johnson@example.com", "1234567890", 50000);
AssistantProfessor assistantProfessor = new AssistantProfessor("Bob Smith", "AP001", "456
Elm St", "bob.smith@example.com", "0987654321", 60000);
AssociateProfessor associateProfessor = new AssociateProfessor("Carol Davis", "AP002", "789
Oak St", "carol.davis@example.com", "1122334455", 70000);
Professor professor = new Professor("Dave Wilson", "P002", "101 Pine St",
"dave.wilson@example.com", "5566778899", 80000);

// Generate pay slips


programmer.generatePaySlip();
assistantProfessor.generatePaySlip();
associateProfessor.generatePaySlip();
professor.generatePaySlip();
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac EmployeeManagement.java

C:\jdk-21.0.2\bin>java EmployeeManagement
Pay Slip for Alice Johnson
Employee ID: P001
Address: 123 Main St
Mail ID: alice.johnson@example.com
Mobile No: 1234567890
Basic Pay: 50000.0
Dearness Allowance (DA): 48500.0
House Rent Allowance (HRA): 5000.0
Provident Fund (PF): 6000.0
Staff Club Funds: 50.0
Gross Salary: 103500.0
Net Salary: 97450.0

Pay Slip for Bob Smith


Employee ID: AP001
Address: 456 Elm St
Mail ID: bob.smith@example.com
Mobile No: 0987654321
Basic Pay: 60000.0
Dearness Allowance (DA): 58200.0
House Rent Allowance (HRA): 6000.0
Provident Fund (PF): 7200.0
Staff Club Funds: 60.0
Gross Salary: 124200.0
Net Salary: 116940.0

Pay Slip for Carol Davis


Employee ID: AP002
Address: 789 Oak St
Mail ID: carol.davis@example.com
Mobile No: 1122334455
Basic Pay: 70000.0
Dearness Allowance (DA): 67900.0
House Rent Allowance (HRA): 7000.0
Provident Fund (PF): 8400.0
Staff Club Funds: 70.0
Gross Salary: 144900.0
Net Salary: 136430.0

Pay Slip for Dave Wilson


Employee ID: P002
Address: 101 Pine St
Mail ID: dave.wilson@example.com
Mobile No: 5566778899
Basic Pay: 80000.0
Dearness Allowance (DA): 77600.0
House Rent Allowance (HRA): 8000.0
Provident Fund (PF): 9600.0
Staff Club Funds: 80.0
Gross Salary: 165600.0
Net Salary: 155920.0
RESULT:
Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named printArea(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each one of
the classes contains only the method printArea( ) that prints the area of the given shape.

EX.NO.:4
DATE:

AIM:

ALGORITHM:
PROGRAM:
AbstractArea.java
import java.util.Scanner;
abstract class Shape {
int a, b;
abstract void printArea(Scanner input);
}

class Rectangle extends Shape {


@Override
void printArea(Scanner input) {
System.out.println("\t\tCalculating Area of Rectangle");
try {
System.out.print("Enter length: ");
a = input.nextInt();
System.out.print("Enter breadth: ");
b = input.nextInt();
int area = a * b;
System.out.println("Area of Rectangle: " + area);
} catch (Exception e) {
System.out.println("Invalid input. Please enter numeric values.");
input.next(); // Clear invalid input
}
}
}

class Triangle extends Shape {


@Override
void printArea(Scanner input) {
System.out.println("\t\tCalculating Area of Triangle");
try {
System.out.print("Enter height: ");
a = input.nextInt();
System.out.print("Enter base: ");
b = input.nextInt();
double area = 0.5 * a * b;
System.out.println("Area of Triangle: " + area);
} catch (Exception e) {
System.out.println("Invalid input. Please enter numeric values.");
input.next(); // Clear invalid input
}
}
}

class Circle extends Shape {


@Override
void printArea(Scanner input) {
System.out.println("\t\tCalculating Area of Circle");
try {
System.out.print("Enter radius: ");
a = input.nextInt();
double area = 3.14 * a * a;
System.out.println("Area of Circle: " + area);
} catch (Exception e) {
System.out.println("Invalid input. Please enter numeric values.");
input.next(); // Clear invalid input
}
}
}

public class AbstractArea {


public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create a single Scanner instance
Shape obj;
obj = new Rectangle();
obj.printArea(input);
obj = new Triangle();
obj.printArea(input);
obj = new Circle();
obj.printArea(input);
input.close(); // Close the Scanner when done
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac AbstractArea.java

C:\jdk-21.0.2\bin>java AbstractArea
Calculating Area of Rectangle
Enter length: 8
Enter breadth: 3
Area of Rectangle: 24
Calculating Area of Triangle
Enter height: 3
Enter base: 3
Area of Triangle: 4.5
Calculating Area of Circle
Enter radius: 5
Area of Circle: 78.5

RESULT:
Write a Java Program to create an abstract class named Shape that contains two integers and an
empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only the
method printArea( ) that prints the area of the given shape. Solve the above problem using an
interface.
EX.NO.: 5
DATE:
AIM:

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()
{
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();
}
}
OUTPUT:

C:\jdk-21.0.2\bin>javac TestArea.java

C:\jdk-21.0.2\bin>java TestArea
Calculating Area of Rectangle
Enter length: 7

Enter breadth: 2
Area of Rectangle: 14
Calculating Area of Triangle
Enter height: 8

Enter breadth: 4
Area of Triangle: 16.0
Calculating Area of Circle
Enter radius: 6
Area of Circle: 113.03999999999999

RESULT:
IMPLEMENT EXCEPTION HANDLING AND CREATION OF USER DEFINED
EXCEPTIONS

EX.NO.: 6
DATE:
AIM:

ALGORITHM:
PROGRAM:
UserDefinedException.java
import java.util.Scanner;
class NegativeAmtException extends Exception {
private String msg;
NegativeAmtException(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return msg;
}
}
class BankAccount {
private double balance;
private int accountNumber;
public BankAccount(int accountNumber, double initialBalance) throws NegativeAmtException {
if (initialBalance < 0) {
throw new NegativeAmtException("Initial amount should not be negative!");
}
this.balance = initialBalance;
this.accountNumber = accountNumber;
}
public void deposit(double amount) throws NegativeAmtException {
if (amount < 0) {
throw new NegativeAmtException("Don't deposit a negative amount!");
}
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 -= amount;
} else {
System.out.println("Insufficient funds");
}
System.out.println("Balance amount: " + getBalance());
}

public double getBalance() {


return balance;
}
public int getAccountNumber() {
return accountNumber;
}
@Override
public String toString() {
return "Account Number: " + accountNumber + " Balance: " + balance;
}
}
public class UserDefinedException {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter Account Number: ");
int accountNumber = sc.nextInt();
System.out.print("Enter the initial Amount: ");
double initialAmount = sc.nextDouble();
BankAccount account = new BankAccount(accountNumber, initialAmount);
while (true) {
System.out.println("Main Menu");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Display Account Details");
System.out.println("5. Exit");
System.out.print("Enter your Choice: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the amount to deposit: ");
double depositAmount = sc.nextDouble();
try {
account.deposit(depositAmount);
} catch (NegativeAmtException e) {
System.out.println("Exception Caught: " + e);
}
break;

case 2:
System.out.print("Enter the amount to withdraw: ");
double withdrawAmount = sc.nextDouble();
try {
account.withdraw(withdrawAmount);
} catch (NegativeAmtException e) {
System.out.println("Exception Caught: " + e);
}
break;
case 3:
System.out.println("Balance amount: " + account.getBalance());
break;
case 4:
System.out.println("Your account details:\n" + account);
break;
case 5:
sc.close();
System.exit(0);
default:
System.out.println("Invalid Choice");
}
}
} catch (NegativeAmtException e) {
System.out.println("Exception Caught: " + e);
}
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac UserDefinedException.java

C:\jdk-21.0.2\bin>java UserDefinedException
Enter Account Number: 10028
Enter the initial Amount: 67000
Main Menu
1. Deposit
2. Withdraw
3. Check Balance
4. Display Account Details
5. Exit
Enter your Choice: 1
Enter the amount to deposit: 45000
Amount deposited
Balance amount: 112000.0
Main Menu
1. Deposit
2. Withdraw
3. Check Balance
4. Display Account Details
5. Exit
Enter your Choice: 2
Enter the amount to withdraw: 56000
Balance amount: 56000.0
Main Menu
1. Deposit
2. Withdraw
3. Check Balance
4. Display Account Details
5. Exit
Enter your Choice: 3
Balance amount: 56000.0
Main Menu
1. Deposit
2. Withdraw
3. Check Balance
4. Display Account Details
5. Exit
Enter your Choice: 2
Enter the amount to withdraw: 67000
Insufficient funds
Balance amount: 56000.0
Main Menu
1. Deposit
2. Withdraw
3. Check Balance
4. Display Account Details
5. Exit

RESULT:
WRITE A JAVA PROGRAM THAT IMPLEMENTS A MULTI-THREADED APPLICATION
THAT HAS THREE THREADS. FIRST THREAD GENERATES A RANDOM INTEGER
EVERY 1 SECOND AND IF THE VALUE IS EVEN, THE SECOND THREAD COMPUTES
THE SQUARE OF THE NUMBER AND PRINTS. IF THE VALUE IS ODD, THE THIRD
THREAD WILL PRINT THE VALUE OF THE CUBE OF THE NUMBER

EX.NO.: 7
DATE:
AIM:

ALGORITHM:
PROGRAM:
MultiThread.java
import java.util.Random;

class Even implements Runnable {


private int x;

public Even(int x) {
this.x = x;
}
@Override
public void run() {
System.out.println("New Thread " + x + " is EVEN and Square of " + x + " is: " + x * x);
}
}

class Odd implements Runnable {


private int x;

public Odd(int x) {
this.x = x;
}

@Override
public void run() {
System.out.println("New Thread " + x + " is ODD and Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread {
@Override
public void run() {
int num;
Random r = new Random();

try {
for (int i = 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 class MultiThread {


public static void main(String[] args) {
A a = new A();
a.start();
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac MultiThread.java

C:\jdk-21.0.2\bin>java MultiThread
Main Thread and Generated Number is 81
New Thread 81 is ODD and Cube of 81 is: 531441
--------------------------------------
Main Thread and Generated Number is 10
New Thread 10 is EVEN and Square of 10 is: 100
--------------------------------------
Main Thread and Generated Number is 67
New Thread 67 is ODD and Cube of 67 is: 300763
--------------------------------------
Main Thread and Generated Number is 76
New Thread 76 is EVEN and Square of 76 is: 5776
--------------------------------------
Main Thread and Generated Number is 19
New Thread 19 is ODD and Cube of 19 is: 6859
--------------------------------------

C:\jdk-21.0.2\bin>

RESULT:
WRITE A PROGRAM TO PERFORM FILE OPERATIONS
EX.NO.: 8
DATE:
AIM:

ALGORITHM:
PROGRAM:
FileCopy.java
import java.io.*;

class CopyFile {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: CopyFile <source> <destination>");
return;
}
String sourceFile = args[0];
String destinationFile = args[1];
System.out.println("Displaying contents of " + sourceFile + "\n");
displayFileContents(sourceFile);
System.out.println("\nCopying contents of " + sourceFile + " to " + destinationFile + "\n");
copyFile(sourceFile, destinationFile);
System.out.println("\nDisplaying contents of " + destinationFile + "\n");
displayFileContents(destinationFile);
}

private static void displayFileContents(String fileName) {


try (FileInputStream fin = new FileInputStream(fileName)) {
int i;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
System.out.println("Error Reading File " + fileName + ": " + e.getMessage());
}
}

private static void copyFile(String sourceFile, String destinationFile) {


try (FileInputStream fin = new FileInputStream(sourceFile);
FileOutputStream fout = new FileOutputStream(destinationFile)) {
int i;
while ((i = fin.read()) != -1) {
fout.write(i);
}
} catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac CopyFile.java
C:\jdk-21.0.2\bin>java CopyFile OOp.txt New.txt
Displaying contents of OOp.txt
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to design
and structure software. It aims to organize code in a way that models real-world entities and their
interactions. OOP is based on several core concepts, which help in creating more modular, reusable,
and maintainable code.
Copying contents of OOp.txt to New.txt

Displaying contents of New.txt

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to design
and structure software. It aims to organize code in a way that models real-world entities and their
interactions. OOP is based on several core concepts, which help in creating more modular, reusable,
and maintainable code.
C:\jdk-21.0.2\bin>
RESULT:
DEVELOP APPLICATIONS TO DEMONSTRATE THE FEATURES
OF GENERICS CLASSES

EX.NO.: 9
DATE:

AIM:

ALGORITHM:
PROGRAM:
GenericsDemo.java
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] obj)
{
vals = obj;
}
public T min()
{
T v = vals[0];
for(int i=1; i<vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i<vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
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:

C:\jdk-21.0.2\bin>java GenericsDemo
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

C:\jdk-21.0.2\bin>

RESULT:
DEVELOP APPLICATIONS USING JAVAFX CONTROLS
EX.NO.: 10(a)
DATE:

AIM:

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

radio2= new RadioButton("20");


radio3= new RadioButton("30");
radio4= new RadioButton("40");

ToggleGroup question1= new ToggleGroup();


radio1.setToggleGroup(question1);
radio2.setToggleGroup(question1);
radio3.setToggleGroup(question1);
radio4.setToggleGroup(question1);

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);
}
}
OUTPUT:

RESULT:
DEVELOP APPLICATIONS USING LAYOUTS AND MENUS
EX.NO.: 10(b)
DATE:

AIM:

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
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);
primaryStage.setTitle("JavaFX Menu");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
OUTPUT:

RESULT:
DEVELOP A MINI PROJECT FOR ANY APPLICATION USING JAVA CONCEPTS
(LIBRARY MANAGEMENT SYSTEM)

EX.NO.: 11
DATE:
AIM:

ALGORITHM:
PROGRAM:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LibraryManagementSystem {

// Book class
static class Book {
private String title;
private String author;
private boolean isBorrowed;

public Book(String title, String author) {


this.title = title;
this.author = author;
this.isBorrowed = false;
}

public String getTitle() {


return title;
}

public String getAuthor() {


return author;
}

public boolean isBorrowed() {


return isBorrowed;
}

public void borrow() {


isBorrowed = true;
}

public void returnBook() {


isBorrowed = false;
}

@Override
public String toString() {
return String.format("Title: %s, Author: %s, Status: %s", title, author, isBorrowed ?
"Borrowed" : "Available");
}
}
// Library class
static class Library {
private List<Book> books;

public Library() {
books = new ArrayList<>();
}

public void addBook(Book book) {


books.add(book);
}

public void listBooks() {


for (Book book : books) {
System.out.println(book);
}
}

public Book searchBookByTitle(String title) {


for (Book book : books) {
if (book.getTitle().equalsIgnoreCase(title)) {
return book;
}
}
return null;
}

public boolean borrowBook(String title) {


Book book = searchBookByTitle(title);
if (book != null && !book.isBorrowed()) {
book.borrow();
return true;
}
return false;
}

public boolean returnBook(String title) {


Book book = searchBookByTitle(title);
if (book != null && book.isBorrowed()) {
book.returnBook();
return true;
}
return false;
}
}
// Main application class
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Library library = new Library();

while (true) {
System.out.println("Library Management System");
System.out.println("1. Add Book");
System.out.println("2. List Books");
System.out.println("3. Search Book");
System.out.println("4. Borrow Book");
System.out.println("5. Return Book");
System.out.println("6. Exit");
System.out.print("Choose an option: ");
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter book author: ");
String author = scanner.nextLine();
library.addBook(new Book(title, author));
System.out.println("Book added successfully.");
break;

case 2:
library.listBooks();
break;

case 3:
System.out.print("Enter book title to search: ");
title = scanner.nextLine();
Book book = library.searchBookByTitle(title);
if (book != null) {
System.out.println(book);
} else {
System.out.println("Book not found.");
}
break;

case 4:
System.out.print("Enter book title to borrow: ");
title = scanner.nextLine();
if (library.borrowBook(title)) {
System.out.println("Book borrowed successfully.");
} else {
System.out.println("Book not available for borrowing.");
}
break;

case 5:
System.out.print("Enter book title to return: ");
title = scanner.nextLine();
if (library.returnBook(title)) {
System.out.println("Book returned successfully.");
} else {
System.out.println("Book not found or not borrowed.");
}
break;

case 6:
System.out.println("Exiting...");
scanner.close();
System.exit(0);
break;

default:
System.out.println("Invalid option. Please try again.");
}
}
}
}
OUTPUT:
C:\jdk-21.0.2\bin>javac LibraryManagementSystem.java

C:\jdk-21.0.2\bin>java LibraryManagementSystem
Library Management System
1. Add Book
2. List Books
3. Search Book
4. Borrow Book
5. Return Book
6. Exit
Choose an option: 1
Enter book title: Object-Oriented Design and Programming
Enter book author: Grady Booch
Book added successfully.
Library Management System
1. Add Book
2. List Books
3. Search Book
4. Borrow Book
5. Return Book
6. Exit
Choose an option: 1
Enter book title: Object-Oriented Programming in C++
Enter book author: Robert Lafore
Book added successfully.
Library Management System
1. Add Book
2. List Books
3. Search Book
4. Borrow Book
5. Return Book
6. Exit
Choose an option: 2
Title: Object-Oriented Design and Programming, Author: Grady Booch, Status: Available
Title: Object-Oriented Programming in C++, Author: Robert Lafore, Status: Available
Library Management System
1. Add Book
2. List Books
3. Search Book
4. Borrow Book
5. Return Book
6. Exit
Choose an option: 3
Enter book title to search: Object-Oriented Programming in C++
Title: Object-Oriented Programming in C++, Author: Robert Lafore, Status: Available
Library Management System
1. Add Book
2. List Books
3. Search Book
4. Borrow Book
5. Return Book
6. Exit
Choose an option:
RESULT:

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy