[go: up one dir, main page]

0% found this document useful (0 votes)
21 views46 pages

Oops Lab 21 R-1

The document describes a lab course on object oriented programming in Java. It lists the course objectives as developing software skills in Java, understanding OOP concepts, and developing applications using generics, exceptions, files and GUI. It then lists 11 lab experiments covering data structures, inheritance, exceptions, threads, files and JavaFX. It also lists the requirements and outcomes of the course.

Uploaded by

dhasamalika
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)
21 views46 pages

Oops Lab 21 R-1

The document describes a lab course on object oriented programming in Java. It lists the course objectives as developing software skills in Java, understanding OOP concepts, and developing applications using generics, exceptions, files and GUI. It then lists 11 lab experiments covering data structures, inheritance, exceptions, threads, files and JavaFX. It also lists the requirements and outcomes of the course.

Uploaded by

dhasamalika
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/ 46

CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY

Course Objectives:
● To build software development skills using java programming for real-world applications.
● To understand and apply the concepts of classes, packages, interfaces, inheritance,
exceptionhandling and file processing.
● To develop applications using generic programming and event handling.
Lab Experiments:
1.Solve problems by using sequential search, binary search, and quadratic sorting algorithms (selection,
insertion)
2. Develop stack and queue data structures using classes and objects.
3. 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.
4. 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.
5. Solve the above problem using an interface.
6. Implement exception handling and creation of user defined exceptions.
7. 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.
8. Write a program to perform file operations.
9. Develop applications to demonstrate the features of generics classes.
10. Develop applications using JavaFX controls, layouts and menus.
11. Develop a mini project for any application using Java concepts.
Lab Requirements:
for a batch of 30 students Operating Systems:
Linux / Windows Front End Tools: Eclipse IDE / NetBeans IDE
TOTAL: 45 PERIODS
Course Outcomes:
On completion of this course, the students will be able to
CO1 : Design and develop java programs using object-oriented programming concepts
CO2 : Develop simple applications using object-oriented concepts such as package, exceptions
CO3: Implement multithreading, and generics concepts
CO4 : Create GUIs and event driven programming applications for real world problems
CO5: Implement and deploy web applications using Java
Ex.No:1.(a) Binary Search
Date:

Aim:
To write the java program to solve problems by using sequential search, binary search, and
quadratic sorting algorithms.

Algorithm:

Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound' is the i
ndex of the first array element, 'upper_bound' is the index of the last array element, 'val' is the val
ue to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit
Program:
class BinarySearch {
static int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{
mid = (beg + end)/2;
if(a[mid] == val)
{
return mid+1; /* if the item to be searched is present at middle */
}
/* if the item to be searched is smaller than middle, then it can only
be in left subarray */
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/* if the item to be searched is greater than middle, then it can only be
in right subarray */
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
public static void main(String args[]) {
int a[] = {8, 10, 22, 27, 37, 44, 49, 55, 69}; // given array
int val = 37; // value to be searched
int n = a.length; // size of array
int res = binarySearch(a, 0, n-1, val); // Store result
System.out.print("The elements of the array are: ");
for (int i = 0; i < n; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println("Element to be searched is: " + val);
if (res == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element is present at " + res + " position of array");
}
}
Output:

Result:
Thus, the program has been executed and output was verified using binary search
successfully.
Ex.No:1.(b) Linear Search
Date:

Aim:
To write the java program to solve problems by using sequential searchalgorithms.
Algorithm:
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' is the value to s
earch Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit
Program:
class LinearSearch {
static int linearSearch(int a[], int n, int val) {
// Going through array sequencially
for (int i = 0; i < n; i++)
{
if (a[i] == val)
return i+1;
}
return -1;
}
public static void main(String args[]) {
int a[] = {55, 29, 10, 40, 57, 41, 20, 24, 45}; // given array
int val = 10; // value to be searched
int n = a.length; // size of array
int res = linearSearch(a, n, val); // Store result
System.out.println();
System.out.print("The elements of the array are - ");
for (int i = 0; i < n; i++)
System.out.print(" " + a[i]);
System.out.println();
System.out.println("Element to be searched is - " + val);
if (res == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element is present at " + res +" position of array");
}
}
Output:

Result:
Thus, the program has been executed and output was verified using binary search successfully.
Ex.No:1.(c) Quadratic Sorting(insertion and Selection)
Date:

Aim:
To write the java program to solve problems by using quadratic sorting algorithms.
Algorithm:
1.SELECTION SORT(arr, n)
Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
Step 2: CALL SMALLEST(arr, i, n, pos)
Step 3: SWAP arr[i] with arr[pos]
[END OF LOOP]
Step 4: EXIT

SMALLEST (arr, i, n, pos)


Step 1: [INITIALIZE] SET SMALL = arr[i]
Step 2: [INITIALIZE] SET pos = i
Step 3: Repeat for j = i+1 to n
if (SMALL > arr[j])
SET SMALL = arr[j]
SET pos = j
[END OF if]
[END OF LOOP]
Step 4: RETURN pos
Program:
public class Selection
{
void selection(int a[]) /* function to sort an array with selection sort */
{
int i, j, small;
int n = a.length;
for (i = 0; i < n-1; i++)
{
small = i; //minimum element in unsorted array

for (j = i+1; j < n; j++)


if (a[j] < a[small])
small = j;
// Swap the minimum element with the first element
int temp = a[small];
a[small] = a[i];
a[i] = temp;
}

}
void printArr(int a[]) /* function to print the array */
{
int i;
int n = a.length;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
public static void main(String[] args) {
int a[] = { 91, 49, 4, 19, 10, 21 };
Selection i1 = new Selection();
System.out.println("\nBefore sorting array elements are - ");
i1.printArr(a);
i1.selection(a);
System.out.println("\nAfter sorting array elements are - ");
i1.printArr(a);
System.out.println();
}
}
Output:

Algorithm:
Step 1 -If the element is the first element, assume that it is already sorted. Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 -If the element in the sorted array is smaller than the current element, then move to the
next element. Else, shift greater elements in the array towards the right.
Step 5 -Insert the value.
Step 6 -Repeat until the array is sorted.
Program:
public class Insert
{
void insert(int a[]) /* function to sort an aay with insertion sort */
{
int i, j, temp;
int n = a.length;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead from th
eir current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[]) /* function to print the array */
{
int i;
int n = a.length;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}

public static void main(String[] args) {


int a[] = { 92, 50, 5, 20, 11, 22 };
Insert i1 = new Insert();
System.out.println("\nBefore sorting array elements are - ");
i1.printArr(a);
i1.insert(a);
System.out.println("\n\nAfter sorting array elements are - ");
i1.printArr(a);
System.out.println();
}
}
Output:

Result:
Thus, the program has been executed and output was verified using quadratic sorting algorithm
successfully.
Ex.No:2 Stack and Queue data structures using Classes and Objects
Date:

Aim:
To write a java program for stack and queue using classes and objects.

Algorithm:
Step:1 Start the program
Step:2 Create a class and name it Stack.
Step:3 Intialize three variables that determine the stack size, the elements themselves, and the top
element.
Step:4 Create constructor0 that is used to initialise the stack with the max size value.
Step:5 An array of that size is created and top is initialised to -1
PUSH operation:
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
POP operation:
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
ENQUEUE Operation:
Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − return success.
DEQUEUE Operation:
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
Program:
Stack Implementation
StackDemo.java
class StackDemo {
public static void main(String[] args) {

Stack<Integer> stack = new Stack<Integer>(5);


System.out.print("Elements pushed in the Stack: ");
for (int i = 0; i < 5; i++) {
stack.push(i); //pushes 5 elements (0-4 inclusive) to the stack
System.out.print(i + " ");
}
System.out.println("\nIs Stack full? \n" + stack.isFull());
System.out.print("Elements popped from the Stack: ");
for (int i = 0; i < 5; i++) {
System.out.print(stack.pop()+" "); //pops all 5 elements from the stack and prints them
}
System.out.println("\nIs Stack empty? \n" + stack.isEmpty());

}//end of main
Stack.java
public class Stack <V> {
private int maxSize;
private int top;
private V array[];

/*
Java does not allow generic type arrays. So we have used an
array of Object type and type-casted it to the generic type V.
This type-casting is unsafe and produces a warning.
Comment out the line below and execute again to see the warning.
*/
@SuppressWarnings("unchecked")
public Stack(int max_size) {
this.maxSize = max_size;
this.top = -1; //initially when stack is empty
array = (V[]) new Object[max_size];//type casting Object[] to V[]
}

//returns the maximum size capacity


public int getMaxSize() {
return maxSize;
}

//returns true if Stack is empty


public boolean isEmpty(){
return top == -1;
}

//returns true if Stack is full


public boolean isFull(){
return top == maxSize -1;
}

//returns the value at top of Stack


public V top(){
if(isEmpty())
return null;
return array[top];
}
//inserts a value to the top of Stack
public void push(V value){
if(isFull()) {
System.err.println("Stack is Full!");
return;
}
array[++top] = value; //increments the top and adds value to updated top
}

//removes a value from top of Stack and returns


public V pop(){
if(isEmpty())
return null;
return array[top--]; //returns value and top and decrements the top
}
}
}

Output:

Elements pushed in the Stack: 0 1 2 3 4


Is Stack full?
true Elements popped from the Stack: 4 3 2 1 0
Is Stack empty? True

Queue Implementation
QueueDemo.java
class QueueDemo {
public static void main(String[] args) {
Queue<Integer> queue = new Queue<Integer>(5);
//equeue 2 4 6 8 10 at the end
queue.enqueue(2);
queue.enqueue(4);
queue.enqueue(6);
queue.enqueue(8);
queue.enqueue(10);
//dequeue 2 elements from the start
queue.dequeue();
queue.dequeue();
//enqueue 12 and 14 at the end
queue.enqueue(12);
queue.enqueue(14);

System.out.println("Queue:");
while(!queue.isEmpty()){
System.out.print(queue.dequeue()+" ");
}
}
}

Queue.java
public class Queue<V> {
private int maxSize;
private V[] array;
private int front;
private int back;
private int currentSize;

/*
Java does not allow generic type arrays. So we have used an
array of Object type and type-casted it to the generic type V.
This type-casting is unsafe and produces a warning.
Comment out the line below and execute again to see the warning.
*/
@SuppressWarnings("unchecked")
public Queue(int maxSize) {
this.maxSize = maxSize;
array = (V[]) new Object[maxSize];
front = 0;
back = -1;
currentSize = 0;
}

public int getMaxSize() {


return maxSize;
}

public int getCurrentSize() {


return currentSize;
}

public boolean isEmpty() {


return currentSize == 0;
}

public boolean isFull() {


return currentSize == maxSize;
}

public V top() {
return array[front];
}

public void enqueue(V value) {


if (isFull())
return;
back = (back + 1) % maxSize; //to keep the index in range
array[back] = value;
currentSize++;
}

public V dequeue() {
if (isEmpty())
return null;

V temp = array[front];
front = (front + 1) % maxSize; //to keep the index in range
currentSize--;

return temp;
}
}

Output:

Queue: 6 8 10 12 14

Result:
Thus the program was executed and output was verified successfully.
Ex.No:3 Program to generate Pay Slip using Inheritance
Date:

Aim:
To develop a java application to generate pay slip for different category of employees
using the concept of inheritance.
Algorithm:
Step:1 Create the class employee with name, Empid, address, mailid, mobileno as members.
Step:2 Inherit the classes programmer, asstprofessor,associateprofessor and professor from
employee class.
Step:3 Add Basic Pay (BP) as the member of all the inherited classes.
Step:4 Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as
0.1% of BP.
Step:5 Calculate gross salary and net salary.
Step:6 Generate payslip for all categories of employees.
Step:7 Create the objects for the inherited classes and invoke the necessary methods to display
the Payslip.
Program:
import java.util.*;
class employee
{
int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner(System.in);
void getdata()
{
System.out.println("Enter Name of the Employee");
name = get.nextLine();
System.out.println("Enter Mail id");
mailid = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();
System.out.println("Enter employee id ");
empid = get.nextInt();
System.out.println("Enter Mobile Number");
mobile = get.nextLong();
}
void display()
{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
System.out.println("Mobile Number: "+mobile);
}
}
class programmer extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROGRAMMER");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class asstprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class associateprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class professor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
void calculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class salary
{
public static void main(String args[])
{
int choice,cont;
do
{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t 3.ASSOCIATE
PROFESSOR \t 4.PROFESSOR ");
Scanner c = new Scanner(System.in);
choice=c.nextInt();
switch(choice)
{
case 1:
{
programmer p=new programmer();
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}
case 2:
{
asstprofessor asst=new asstprofessor();
asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
}
case 3:
{
associateprofessorasso=new associateprofessor();
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case 4:
{
professor prof=new professor();
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
}
}
System.out.println("Do u want to continue 0 to quit and 1 to continue ");
cont=c.nextInt();
}while(cont==1);
}
}
Output:
Result:
The java application to generate pay slip for different category of employees was
implemented using inheritance and the program was executed successfully.
Ex.No:4 Program to calculate area using Abstract Class
Date:

Aim:
To write a java program to calculate the area of rectangle,circle and triangle using the
concept of abstract class.
Algorithm:
1. Create an abstract class named shape that contains two integers and an empty method
named
printarea().

2. Provide three classes named rectangle, triangle and circle such that each one of the
classes
extends the class Shape.

3.Each of the inherited class from shape class should provide the implementation for the
methodprintarea().
4.Get the input and calculate the area of rectangle,circle and triangle .

5. In the shapeclass , create the objects for the three inherited classes and invoke the
methods and display the area values of the different shapes.
Program:
import java.util.*;
abstract class shape
{
int a,b;
abstract public void printarea();
}
class rectangle extends shape
{
public int area_rect;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the length and breadth of rectangle");
a=s.nextInt();
b=s.nextInt();
area_rect=a*b;
System.out.println("Length of rectangle "+a +"breadth of rectangle "+b);
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
double area_tri;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the base and height of triangle");
a=s.nextInt();
b=s.nextInt();
System.out.println("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
double area_circle;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the radius of circle");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radius of circle"+a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class shapeclass
{
public static void main(String[] args)
{
rectangle r=new rectangle();
r.printarea();
triangle t=new triangle();
t.printarea();
circle r1=new circle();
r1.printarea();
}
}
Output:

Result:

Thus, a java program for calculate the area of rectangle,circle and triangle was
implemented and executed successfully.
Ex.No:5 Program to calculate area using Interface
Date:

Aim:
To write a java program to calculate the area of rectangle,circle and triangle using the
concept of Interface.
Algorithm:
Step:1Create an Interface named shape that contains two integers and an empty method
named printarea().
Step:2 Provide three classes named rectangle, triangle and circle such that each one of
the classes extends the class Shape.
Step:3 Each of the inherited class from shape class should provide the implementation for
the method printarea().
Step:4 Get the input and calculate the area of rectangle,circle and triangle .
Step:5 In the shapeclass , create the objects for the three inherited classes and invoke the
methods and display the area values of the different shapes.
Program:
interface Shape
{
void input();
void printarea();
}
class Circle implements Shape
{
int r = 0;
double pi = 3.14, ar = 0;
@Override
public void input()
{
r = 5;
}
@Override
public void printarea()
{
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
}
}
class Rectangle extends Circle
{
int l = 0, b = 0;
double ar;
public void input()
{
super.input();
l = 6;
b = 4;
}
public void printarea()
{
super.printarea();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
}
}
public class Demo
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.input();
obj.printarea();
}
}

Output:

$ javac Demo.java
$ java Demo

Area of circle: 78.5


Area of rectangle: 24.0
Ex.No:6 Program to implement user defined exceptionhandling
Date:
-

Aim:
To write a java program to implement user defined exception handling.
Algorithm:
Step1.Create a class which extends Exception class.
Step:2 Create a constructor which receives the string as argument.
Step3 Get the Amount as input from the user.
Step 4 If the amount is negative , the exception will be generated.
Step 5 Using the exception handling mechanism , the thrown exception is handled by the
catch construct.
Step:6 After the exception is handled , the string “invalid amount “ will be displayed.
Step:7 If the amount is greater than 0 , the message “Amount Deposited “ will be
displayed.
(A)Program:
import java.util.Scanner;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}

Output:

(B) Program:

class MyException extends Exception{


String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{
return ("MyException Occurred: "+str1) ;
}
}
class example
{
public static void main(String args[])
{
try
{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block") ;
System.out.println(exp) ;
}}}

Output:

Result:

Thus, a java program to implement user defined exception handling has been implemented and
executed successfully.
Ex.No:7 Program to implement Multithreaded Application
Date:

Aim:
To write a java program that implements a multi-threaded application .

Algorithm:

Step:1Create a class even which implements first thread that computes .the square of the
number .
Step:2 run() method implements the code to be executed when thread gets executed.
Step:3 Create a class odd which implements second thread that computes the cube of the
number.
Step:4 Create a third thread that generates random number.If the random number is even ,
it displays the square of the number.If the random number generated is odd , it
displays the cube of the given number .
Step:5 The Multithreading is performed and the task switched between multiple threads.
Step:6 The sleep () method makes the thread to suspend for the specified time.

Program:
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;
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()
{
int num = 0;
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 multithreadprog
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
Output:

Result:
Thus a java program for multi-threaded application has been implemented and executed
successfully.
Ex.No:8 Program for displaying File Information
Date:

Aim:
To write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of
the file in bytes.
Algorithm:
Step:1 Create a class filedemo. Get the file name from the user .
Step:2 Use the file functions and display the information about the file.
Step:3 getName() displays the name of the file.
Step:4 getPath() diplays the path name of the file.
Step:5 getParent () -This method returns the pathname string of this abstract pathname’s
parent, or null if this pathname does not name a parent directory.
Step:6 exists() – Checks whether the file exists or not.
Step:7 canRead()-This method is basically a check if the file can be read.
Step:8 canWrite()-verifies whether the application can write to the file.
Step:9 isDirectory() – displays whether it is a directory or not.
Step:10 isFile() – displays whether it is a file or not.
Step:11 lastmodified() – displays the last modified information.
Step:12 length()- displays the size of the file.
Step:13 delete() – deletes the file
Step:14 Invoke the predefined functions abd display the iformation about the file.
Program:
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.nextLine();
File f1=new File(filename);
System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}

Output:
Result:

Thus a java program to display file information has been implemented and executed
successfully.
Ex.No:9 Program for Generic class
Date:

Aim:
To write the java program to develop generic features.
Algorithm:
Step:1 Start the process
Step:2 create the class using generic
Step:3 create array which is have some defined list
Step:4 use features of generic ,have compile error and type casting method on the list of
values.
Step :5 write the code to compare the values in list of generic values.
Step:6 Display the result and stop the process
Program:
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error

String s=list.get(1);//type casting is not required


System.out.println("element is: "+s);

Iterator<String>itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:

C:/>javac TestGenerics1.java
C:/> java TestGenerics1
element is: jai
rahul
jai

Result:
Thus, a java program for generic features has been executed and output was verified
successfully.
Ex.No:10 Registration form using JavaFX
Date:

Aim:
To write a javaFX program for simple registration form using controls and layout.
Algorithm:
Step:1 The first step is to instantiate the class of the respective concept which the user wants to
apply.
Step:2 After instantiating the class, the next step is to set of properties of the instantiated class
Step:3.once complete instantiating classes, define functions of respective field.
Step:4 Run the code using javaFX windows.
Step:5 Show the result
Step:6 Stop the program.
Program:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;
public class RegistrationFormApplication extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Registration Form JavaFX Application");

// Create the registration form grid pane


GridPane gridPane = createRegistrationFormPane();
// Add UI controls to the registration form grid pane
addUIControls(gridPane);
// Create a scene with registration form grid pane as the root node
Scene scene = new Scene(gridPane, 800, 500);
// Set the scene in primary stage
primaryStage.setScene(scene);

primaryStage.show();
}
private GridPane createRegistrationFormPane() {
// Instantiate a new Grid Pane
GridPane gridPane = new GridPane();
// Position the pane at the center of the screen, both vertically and horizontally
gridPane.setAlignment(Pos.CENTER);
// Set a padding of 20px on each side
gridPane.setPadding(new Insets(40, 40, 40, 40));
// Set the horizontal gap between columns
gridPane.setHgap(10);
// Set the vertical gap between rows
gridPane.setVgap(10);
// Add Column Constraints
// columnOneConstraints will be applied to all the nodes placed in column one.
ColumnConstraints columnOneConstraints = new ColumnConstraints(100, 100,
Double.MAX_VALUE);
columnOneConstraints.setHalignment(HPos.RIGHT);
// columnTwoConstraints will be applied to all the nodes placed in column two.
ColumnConstraints columnTwoConstrains = new ColumnConstraints(200,200,
Double.MAX_VALUE);
columnTwoConstrains.setHgrow(Priority.ALWAYS);
gridPane.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);
return gridPane;
}
private void addUIControls(GridPane gridPane) {
// Add Header
Label headerLabel = new Label("Registration Form");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 24));
gridPane.add(headerLabel, 0,0,2,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
// Add Name Label
Label nameLabel = new Label("Full Name : ");
gridPane.add(nameLabel, 0,1);
// Add Name Text Field
TextField nameField = new TextField();
nameField.setPrefHeight(40);
gridPane.add(nameField, 1,1);
// Add Email Label
Label emailLabel = new Label("Email ID : ");
gridPane.add(emailLabel, 0, 2);
// Add Email Text Field
TextField emailField = new TextField();
emailField.setPrefHeight(40);
gridPane.add(emailField, 1, 2);
// Add Password Label
Label passwordLabel = new Label("Password : ");
gridPane.add(passwordLabel, 0, 3);
// Add Password Field
PasswordField passwordField = new PasswordField();
passwordField.setPrefHeight(40);
gridPane.add(passwordField, 1, 3);
// Add Submit Button
Button submitButton = new Button("Submit");
submitButton.setPrefHeight(40);
submitButton.setDefaultButton(true);
submitButton.setPrefWidth(100);
gridPane.add(submitButton, 0, 4, 2, 1);
GridPane.setHalignment(submitButton, HPos.CENTER);
GridPane.setMargin(submitButton, new Insets(20, 0,20,0));
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if(nameField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!",
"Please enter your name");
return;
}
if(emailField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!",
"Please enter your email id");
return;
}
if(passwordField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!",
"Please enter a password");
return;
}

showAlert(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(),
"Registration Successful!", "Welcome " + nameField.getText());
}
});
}
private void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:

Result:
Thus, a java program has been executed and output was verified successfully.
Ex.No:11 A mini-Project: Broadcasting chat server
Date:

Objective/ Vision

Users can interact to each other. They can share information to all others.

Software Requirement to run this project


JRE
Procedure:

● Run the server first, write: java MyServer


● Now click on the executable jar file MyClient as many as you want. It will open different dialog
boxes. Now try to communicate with each other.
● click on the login button and enter your name, now you can share information.

Program:
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*************************/
class MyServer
{
ArrayList al=new ArrayList();
ArrayList users=new ArrayList();
ServerSocket ss;
Socket s;

public final static int PORT=10;


public final static String UPDATE_USERS="updateuserslist:";
public final static String LOGOUT_MESSAGE="@@logoutme@@:";
public MyServer()
{
try{
ss=new ServerSocket(PORT);
System.out.println("Server Started "+ss);
while(true)
{
s=ss.accept();
Runnable r=new MyThread(s,al,users);
Thread t=new Thread(r);
t.start();
// System.out.println("Total alive clients : "+ss.);
}
}
catch(Exception e){System.err.println("Server constructor"+e);}
}
/////////////////////////
public static void main(String [] args)
{
new MyServer();
}
/////////////////////////
}
/*************************/
class MyThread implements Runnable
{
Socket s;
ArrayList al;
ArrayList users;
String username;
///////////////////////
MyThread (Socket s, ArrayListal,ArrayList users)
{
this.s=s;
this.al=al;
this.users=users;
try{
DataInputStream dis=new DataInputStream(s.getInputStream());
username=dis.readUTF();
al.add(s);
users.add(username);
tellEveryOne("****** "+ username+" Logged in at "+(new Date())+" ******");
sendNewUserList();
}
catch(Exception e){System.err.println("MyThread constructor "+e);}
}
///////////////////////
public void run()
{
String s1;
try{
DataInputStream dis=new DataInputStream(s.getInputStream());
do
{
s1=dis.readUTF();
if(s1.toLowerCase().equals(MyServer.LOGOUT_MESSAGE)) break;
// System.out.println("received from "+s.getPort());
tellEveryOne(username+" said: "+" : "+s1);
}
while(true);
DataOutputStreamtdos=new DataOutputStream(s.getOutputStream());
tdos.writeUTF(MyServer.LOGOUT_MESSAGE);
tdos.flush();
users.remove(username);
tellEveryOne("****** "+username+" Logged out at "+(new Date())+" ******");
sendNewUserList();
al.remove(s);
s.close();

}
catch(Exception e){System.out.println("MyThreadRun"+e);}
}
////////////////////////
public void sendNewUserList()
{
tellEveryOne(MyServer.UPDATE_USERS+users.toString());

}
////////////////////////
public void tellEveryOne(String s1)
{
Iterator i=al.iterator();
while(i.hasNext())
{
try{
Socket temp=(Socket)i.next();
DataOutputStream dos=new DataOutputStream(temp.getOutputStream());
dos.writeUTF(s1);
dos.flush();
//System.out.println("sent to : "+temp.getPort()+" : "+ s1);
}
catch(Exception e){System.err.println("TellEveryOne "+e);}
}
}
///////////////////////
}
/*********************************/
class MyClient implements ActionListener
{
Socket s;
DataInputStream dis;
DataOutputStream dos;

JButtonsendButton, logoutButton,loginButton, exitButton;


JFramechatWindow;
JTextAreatxtBroadcast;
JTextAreatxtMessage;
JListusersList;

//////////////////////////
public void displayGUI()
{
chatWindow=new JFrame();
txtBroadcast=new JTextArea(5,30);
txtBroadcast.setEditable(false);
txtMessage=new JTextArea(2,20);
usersList=new JList();
sendButton=new JButton("Send");
logoutButton=new JButton("Log out");
loginButton=new JButton("Log in");
exitButton=new JButton("Exit");

JPanel center1=new JPanel();


center1.setLayout(new BorderLayout());
center1.add(new JLabel("Broad Cast messages from all online users",JLabel.CENTER),"North");
center1.add(new JScrollPane(txtBroadcast),"Center");

JPanel south1=new JPanel();


south1.setLayout(new FlowLayout());
south1.add(new JScrollPane(txtMessage));
south1.add(sendButton);

JPanel south2=new JPanel();


south2.setLayout(new FlowLayout());
south2.add(loginButton);
south2.add(logoutButton);
south2.add(exitButton);

JPanel south=new JPanel();


south.setLayout(new GridLayout(2,1));
south.add(south1);
south.add(south2);

JPanel east=new JPanel();


east.setLayout(new BorderLayout());
east.add(new JLabel("Online Users",JLabel.CENTER),"East");
east.add(new JScrollPane(usersList),"South");

chatWindow.add(east,"East");

chatWindow.add(center1,"Center");
chatWindow.add(south,"South");

chatWindow.pack();
chatWindow.setTitle("Login for Chat");
chatWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
chatWindow.setVisible(true);
sendButton.addActionListener(this);
logoutButton.addActionListener(this);
loginButton.addActionListener(this);
exitButton.addActionListener(this);
logoutButton.setEnabled(false);
loginButton.setEnabled(true);
txtMessage.addFocusListener(new FocusAdapter()
{public void focusGained(FocusEventfe){txtMessage.selectAll();}});

chatWindow.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEventev)
{
if(s!=null)
{
JOptionPane.showMessageDialog(chatWindow,"u are logged out right now.
","Exit",JOptionPane.INFORMATION_MESSAGE);
logoutSession();
}
System.exit(0);
}
});
}
///////////////////////////
public void actionPerformed(ActionEventev)
{
JButton temp=(JButton)ev.getSource();
if(temp==sendButton)
{
if(s==null)
{JOptionPane.showMessageDialog(chatWindow,"u r not logged in. plz login first"); return;}
try{
dos.writeUTF(txtMessage.getText());
txtMessage.setText("");
}
catch(Exception excp){txtBroadcast.append("\nsend button click :"+excp);}
}
if(temp==loginButton)
{
String uname=JOptionPane.showInputDialog(chatWindow,"Enter Your lovely nick name: ");
if(uname!=null)
clientChat(uname);
}
if(temp==logoutButton)
{
if(s!=null)
logoutSession();
}
if(temp==exitButton)
{
if(s!=null)
{
JOptionPane.showMessageDialog(chatWindow,"u r logged out right now.
","Exit",JOptionPane.INFORMATION_MESSAGE);
logoutSession();
}
System.exit(0);
}
}
///////////////////////////
public void logoutSession()
{
if(s==null) return;
try{
dos.writeUTF(MyServer.LOGOUT_MESSAGE);
Thread.sleep(500);
s=null;
}
catch(Exception e){txtBroadcast.append("\n inside logoutSessionMethod"+e);}

logoutButton.setEnabled(false);
loginButton.setEnabled(true);
chatWindow.setTitle("Login for Chat");
}
//////////////////////////
public void clientChat(String uname)
{
try{
s=new Socket(InetAddress.getLocalHost(),MyServer.PORT);
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
ClientThreadct=new ClientThread(dis,this);
Thread t1=new Thread(ct);
t1.start();
dos.writeUTF(uname);
chatWindow.setTitle(uname+" Chat Window");
}
catch(Exception e){txtBroadcast.append("\nClient Constructor " +e);}
logoutButton.setEnabled(true);
loginButton.setEnabled(false);
}
///////////////////////////////
public MyClient()
{
displayGUI();
// clientChat();
}
///////////////////////////////
public static void main(String []args)
{
new MyClient();
}
//////////////////////////
}
/*********************************/
class ClientThread implements Runnable
{
DataInputStream dis;
MyClient client;

ClientThread(DataInputStreamdis,MyClient client)
{
this.dis=dis;
this.client=client;
}
////////////////////////
public void run()
{
String s2="";
do
{
try{
s2=dis.readUTF();
if(s2.startsWith(MyServer.UPDATE_USERS))
updateUsersList(s2);
else if(s2.equals(MyServer.LOGOUT_MESSAGE))
break;
else
client.txtBroadcast.append("\n"+s2);
int lineOffset=client.txtBroadcast.getLineStartOffset(client.txtBroadcast.getLineCount()-
1);
client.txtBroadcast.setCaretPosition(lineOffset);
}
catch(Exception e){client.txtBroadcast.append("\nClientThread run : "+e);}
}
while(true);
}
//////////////////////////
public void updateUsersList(String ul)
{
Vector ulist=new Vector();

ul=ul.replace("[","");
ul=ul.replace("]","");
ul=ul.replace(MyServer.UPDATE_USERS,"");
StringTokenizerst=new StringTokenizer(ul,",");

while(st.hasMoreTokens())
{
String temp=st.nextToken();
ulist.add(temp);
}
client.usersList.setListData(ulist);
}
/////////////////////////
}
/************************/
Output:

Welcome Page

Result:
Thus, a java program was executed and output was verified successfully.

You might also like