0% found this document useful (0 votes)
20 views50 pages

CS3381 OOP - LAB Manual II CSE NEW

Oop manual

Uploaded by

anbesivam548
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)
20 views50 pages

CS3381 OOP - LAB Manual II CSE NEW

Oop manual

Uploaded by

anbesivam548
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/ 50

AVS COLLEGE OF TECHNOLOGY

Attur Main Road, Near AVS College of Arts and Science,


Chinnagoundapuram, Salem – 636 106

Department of Computer Science and Engineering


II Year / III Semester

LAB MANUAL
CS3381 – OBJECT ORIENTED PROGRAMMING LABORATORY

Prepared By

Mr. V.GURUNATHAN
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS3381-OBJECT ORIENTED PROGRAMMING LABORATORY

OBJECTIVES:

 To build software development skills using java programming for real-world


applications.
 To understand and apply the concepts of classes, packages, interfaces, arraylist,
exception handling and file processing.
 To develop applications using generic programming and event handling.

LIST OF 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) LINEAR SEARCH
DATE:

AIM

To write a java Program to implement the linear search algorithm.

ALGORITHM:

1. Start
2. Import the needed packages.
3. Declare the variables.
4. Get the number of elements in the array and store it in a variable n.
5. Get the elements of the array.
6. Get the value to be searched and store in the variable data.
7. Check the value in data with the elements in the array.
8. Once the data is found ,print the location of the data.
9. When the data is not found in the array, print the data is not in the array.
10. Stop

PROGRAM:

import java.io.*;
import java.util.Scanner;
public class LinearSearch
{
public static void main(String args[])
{
int i, n, data, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements:");
n = in.nextInt();
array = new int[n];
for (i = 0;i< n; i++)
{
System.out.println("Enter the element:"+(i+1));
array[i] = in.nextInt();
}
System.out.println("Enter value to find");
data = in.nextInt();
for (i = 0; i< n; i++)
{
if (array[i] == data)
{
System.out.println(data + " is present at location " + (i+ 1) );
break;

}
}
if (i== n)
System.out.println(data +" is not present in the array");
}
}
OUTPUT:

RESULT:

Thus the java program for linear search has been implemented successfully.
EX NO: 1.b) BINARY SEARCH
DATE:

AIM:

To write a java program to implement the binary search algorithm.

ALGORITHM:

1. Start
2. Import the needed header files.
3. Declare an array variable arr.
4. Store the data to be searched in the key variable.
5. Find the element in the middle position .
6. Compare the key elements with the middle element.
7. If key = middle element, then return the mid index position.
8. If key>middle element, then the key lies in the right half of the array. Repeat steps 4,5 and 6
on the right half of the array.
9. If key<middle element, then the key lies in the left half of the array. Repeat steps 4,5 and 6
on the left half of the array.
10. Stop

PROGRAM:

import java.lang.*;
import java.util.*;
import java.io.*;
class Binary
{
public static void binarysearch(int arr[], int first, int last, int key)
{
int pos;
int mid = (first + last)/2;
while( first <last )
{
if ( arr[mid] <key )
{
first = mid + 1;
}else if ( arr[mid] == key )
{

pos=mid+1;
System.out.println("Element is found at index: " + pos);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
System.out.println("Element is not found!");
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter the number of elements");
n=sc.nextInt();
int arr[]=new int[n];
System.out.println("Enter the elements:");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the element to be searched");
int key = sc.nextInt();
int last=arr.length-1;
binarysearch(arr,0,last,key);
}

OUTPUT:

RESULT :

Thus the binary search algorithm is successfully implemented in java.


EX NO: 1.c) SELECTION SORT
DATE

AIM:

To write a java program to implement Selection sort.

ALGORITHM:

1. Start
2. Set MIN to location 0
3. Search the minimum element in the list
4. Swap with value at location MIN
5. Increment MIN to point to next element
6. Repeat until the list is sorted
7. Stop

PROGRAM:

import java.util.*;
class SelectionSort
{
public static void main(String args[])
{
int size;
Scanner in=new Scanner(System.in);
System.out.println("Enter the no.of elements in the array");
size=in.nextInt();
int array[]=new int[size];
System.out.println("Enter the elements");
for(int j=0;j<size;j++)
{
array[j]=in.nextInt();
}

for(int i = 0 ;i< size-1; i++)


{
int min = i;
for (int j = i+1; j<size; j++)
{
if (array[j] < array[min])
{
min = j;
}
}
int temp = array[min];
array[min] = array[i];
array[i] = temp;
}
System.out.println("The sorted array is");
for (int i = 0 ;i< size; i++)
{
System.out.print(" "+array[i]);
}
}
}
OUTPUT:

RESULT:

Thus the java program to implement selection sort was executed successfully.
EX NO: 1.d) INSERTION SORT
DATE

AIM:

To write a java program to implement the insertion sort in java.

ALGORITHM:

1. Start
2. If the element is the first element, assume that it is already sorted. Return 1.
3. Pick the next element, and store it separately in a key.
4. Now, compare the key with all elements in the sorted array.
5. 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.
6. Insert the value.
7. Repeat until the array is sorted.
8. Stop

PROGRAM:

import java.util.*;
class InsertionSort
{
public static void sortInsertion(int[] arr)
{

for(int i=0;i<arr.length;++i)
{

int j = i;

while(j > 0 && arr[j-1]>arr[j])


{

int key = arr[j];


arr[j] = arr[j-1];
arr[j-1] = key;
j = j-1;

}
}
}

public static void main( String args[] )


{
int n;
Scanner in=new Scanner(System.in);
System.out.println("Enter the no.of elements in the array");
n=in.nextInt();
int arr[]=new int[n];
System.out.println("Enter the elements in the array");
for(int j=0;j<n;j++)
{
arr[j]=in.nextInt();
}
sortInsertion(arr);
System.out.println("The Sorted array is");
for(int i=0;i<arr.length;++i)
{
System.out.print(arr[i] + " ");
}
}
}

OUTPUT:

RESULT:

Thus the java program for insertion sort has been implemented successfully.
EX.NO: 2.a) STACK
DATE :

AIM:

To design a java application to implement Stack using classes and objects.

ALGORITHM:

1. Start
2. Include the needed header file.
3. Create a class named Operation.
4. Define all the stack operations.
5. Create a main class named StackExample.
6. Create a Stack.
7. Get the choice from the user for the stack operations.
8. Using the object invoke all the stack functions.
9. Stop

PROGRAM:
import java.util.*;
class Operation
{
void push(Stack<Integer>stack,int a)
{
stack.push(a);
}
void pop(Stack<Integer> stack)
{
int ele=(Integer)stack.pop();
System.out.println("The popped element:"+ele);
}
void peek(Stack<Integer> stack)
{
int ele=(Integer)stack.peek();
System.out.println("The top element of the stack:"+ele);
}
void search(Stack<Integer>stack,int a)
{
int pos=(Integer)stack.search(a);
if(pos==0)
System.out.println("Element not found");
else
System.out.println("Element is found in the position"+pos);
}

class StackExample
{
public static void main(String[] args)
{
Stack<Integer> stack= new Stack<Integer>();
Scanner in=new Scanner(System.in);
Operation ob=new Operation();
int ch,data;
do
{
System.out.println("\n1.Push\n2.Pop\n3.Peek\n4.Search\n5.Exit\nEnter the choice:");
ch=in.nextInt();

switch(ch)
{
case 1:
System.out.println("Enter the data");
data=in.nextInt();
ob.push(stack,data);
System.out.println("Elements in the stack:"+stack);
break;
case 2:
ob.pop(stack);
System.out.println("Elements in the stack:"+stack);
break;
case 3:
ob.peek(stack);
break;
case 4:
System.out.println("Enter the data to be searched");
data=in.nextInt();
ob.search(stack,data);
break;
case 5:
ch=0;
break;
default:
System.out.println("Enter the proper choice");
}
}while(ch>0);
}
}
OUTPUT:

RESULT:

Thus the java application to implement Stack using classes and objects was executed successfully.
EX.NO: 2.b) QUEUE
DATE:

AIM:

To design a java application to implement Queue using classes and objects.

ALGORITHM:

1. Start the program.


2. Include the needed header file.
3. Create a class named Operation.
4. Define all the queue operations.
5. Create a main class named QueueExample.
6. Create a Queue.
7. Get the choice from the user for the queue operations.
8. Using the object invoke all the queue functions.
9. Stop the program.

PROGRAM:

import java.util.*;
class Operation
{
void enqueue(Queue<Integer> queue,int a)
{
queue.add(a);
}
void dequeue(Queue<Integer> queue)
{
int ele=(Integer)queue.poll();
System.out.println("The popped element:"+ele);
}
void peek(Queue<Integer> queue)
{
int ele=(Integer)queue.peek();
System.out.println("The head of the queue:"+ele);
}
}
class QueueExample
{
public static void main(String[] args)
{
Queue<Integer> queue= new LinkedList<Integer>();
Scanner in=new Scanner(System.in);
Operation ob=new Operation();
int ch,data,value;
do
{
System.out.println("\n1.Enqueue\n2.Dequeue\n3.Peek\n4.Exit\nEnter the
choice:");
ch=in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the data");
data=in.nextInt();
ob.enqueue(queue,data);
System.out.println("Elements in the queue:"+queue);
break;
case 2:
ob.dequeue(queue);
System.out.println("Elements in the queue:"+queue);
break;
case 3:
ob.peek(queue);
break;
case 4:
ch=0;
break;
default:
System.out.println("Enter the proper choice ");
}

}while(ch>0);
}
}
OUTPUT:

RESULT:

Thus the java application to implement Queue using classes and objects was executed successfully.
EX NO: 3 PAYSLIP GENERATION USING INHERITANCE
DATE:

AIM:

To develop a java application with 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 fund. Generate pay slips for the employees with their gross and net salary.
.
ALGORITHM:

1. Create the class Employee with name,Empid,address,mailid,mobile no as data members.


2. Inherit the classes Programmer,Asstprofessor,Associateprofessor and Professor from employee
class.
3. Add Basic Pay(BP) as the member of all the inherited classes.
4. Calculate DA as 97% of BP,HRA as 10% of BP, PF as12%ofBP,Staffclubfund as 0.1% of BP.
5. Calculate grosssalary and netsalary.
6. Generate payslip for all categories of employees.
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 sc = new Scanner(System.in);
void getdata()
{
System.out.println("Enter Name of the Employee");
name = sc.nextLine();
System.out.println("Enter Mail id");
mailid = sc.nextLine();
System.out.println("Enter Address of the Employee:");
address =sc.nextLine();
System.out.println("Enter employee id ");
empid = sc.nextInt();
System.out.println("Enter Mobile Number");
mobile = sc.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 = sc.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("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 Asstprofessor extends Employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enter basic pay");
bp = sc.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 = sc.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 =sc.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
{
Scanner sc = new Scanner(System.in);
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \n2.ASSISTANT PROFESSOR \n 3.ASSOCIATE PROFESSOR \n
4.PROFESSOR ");
System.out.println("Enter Your Choice:");
choice=sc.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:
{
Associateprofessor asso=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;
}
default:
System.out.println(“Enter the proper choice:”);
}
System.out.print("Please enter 0 to quit and 1 to continue: ");
cont=sc.nextInt();
}while(cont==1);
}
}
OUTPUT:

RESULT

Thus 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 ABSTRACT CLASS
DATE :

AIM:

To 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.

ALGORITHM:

1. Start the program.


2. Create an abstract class as Shape it contains two integers and one abstact method as printArea().
3. Create the classes Rectangle,Triangle and Circle which extends from the class Shape.
4. Calculate the area of the given shape in the method printArea().
5. Stop the program.

PROGRAM:

import java.util.*;
abstract class Shape
{
public int x, y;
public abstract void printArea();
}
class Rectangle extends Shape
{
public void printArea()
{
System.out.println("Area of Rectangle is " + x * y);
}
}
class Triangle extends Shape
{
public void printArea()
{
System.out.println("Area of Triangle is " + (x * y) / 2);
}

}
class Circle extends Shape
{
public void printArea()
{
System.out.println("Area of Circle is " + (22 * x * x) / 7);
}
}
class AbstractExample
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

Rectangle r = new Rectangle();


System.out.println("Rectangle");
System.out.println("Enter the length:");
r.x = sc.nextInt();
System.out.println("Enter the breadth:");
r.y = sc.nextInt();
r.printArea();
System.out.println("Triangle");
22
Triangle t = new Triangle();
System.out.println("Enter the base:");
t.x = sc.nextInt();
System.out.println("Enter the height:");
t.y = sc.nextInt();
t.printArea();
System.out.println("Circle");
Circle c = new Circle();
System.out.println("Enter the radius:");
c.x = sc.nextInt();
c.printArea();
}
}

23
OUTPUT:

RESULT:

Thus the program for calculating the area of the given shape using abstract class was executed successfully.
EX.NO : 5 INTERFACES
DATE :

AIM:

To write a Java Program to create interfaces named Data and Method that contains two integers and an empty
method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one of the
classes implements the interfaces Data and Method . Each one of the classes contains only the method print Area () that
prints the area of the given shape.

ALGORITHM:

1. Start the program.


2. Create an interface as Data with 2 integers and another interface as Method that contains themethod
printArea().
3. Create a classes as Rectangle,Triangle and Circle which implements the interfaces Data and Method.
4. Calculate the area of the given shapes in the method printArea().
5. Stop the program.

PROGRAM:

interface Data
{
static final int x=24,y=45;
}
interface Method
{
public void printArea();
}
class Rectangle implements Data ,Method
{
public void printArea()
{
System.out.println("Area of Rectangle is " + (x * y));
}
}
class Triangle implements Data,Method
{
void printArea()
{
System.out.println("Area of Triangle is " + (x * y) / 2);
}
}
class Circle implements Data,Method
{
public void printArea()
{
System.out.println("Area of Circle is " + (22 * x * x) / 7);
}
}
class MainShape
{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
Circle c = new Circle();
r.printArea();
t.printArea();
c.printArea();
}
}
25
OUTPUT:

RESULT:

Thus the java program to implement the interface for calculating the area of the given shape was executed
successfully.
EX. NO:6 IMPLEMENT USER DEFINED EXCEPTION HANDLING
DATE :

AIM:

To write a Java program to implement user defined exception handling.

ALGORITHM:

1. Start the program .


2. Get input from the user.
3. If the number is negative throw a exception.
4. Else find the square root of the given number and display it.
5. Stop the program.

PROGRAM:

import java.util.*;
import java.io.*;
class MyException extends Exception
{
MyException(String str)
{
System.out.println(str);
}
}

class ExceptionExample
{
public static void main(String a[])
{
int no;
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number :");
no=sc.nextInt();
if(no<0)
{
throw new MyException("Number must be positive");
}
else
{
System.out.println(" Square root :"+Math.sqrt(no));
}
}
catch(Exception e)
{

}
}

27
OUTPUT:

RESULT:

Thus the program for user defined exception handling was executed successfully.
EX. NO:7 MULTI THREADING IMPLEMENTATION
DATE :

AIM:

To 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, second thread computes the square of the number
and prints. If the value is odd, the third thread will print the value of cube of the number.

ALGORITHM:

1. Start the program.


2. First thread generates random number every 1 second.
3. If even, computes square of number
4. If odd, computes cube of number.
5. Display the square and cube values.
6. Stop the program.

PROGRAM:

import java.util.*;
import java.lang.*;
class EvenThread implements Runnable
{
public int x;
public EvenThread(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN \n Square of " + x + " is: " + x *x);
}
}
class OddThread implements Runnable
{
public int x;
public OddThread(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD\n Cube of " + x + " is: " + x * x *x);
}
}
class RandomThread 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("Generated Random Number is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new EvenThread(num));
29
t1.start();
}
else
{
Thread t2 = new Thread(new OddThread(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
public class ThreadExample
{
public static void main(String args[])
{
RandomThread rt = new RandomThread();
rt.start();
}
}

30
OUTPUT:

RESULT:

Thus the program for multithreading was executed successfully .


EX. NO:8 FILE HANDLING
DATE :

AIM

To write a Java program that performs different file operations

ALGORITHM:

1. Start the program.


2. Get the filename from the user and create a new file.
3. Read the data from the file student.txt
4. Copy the data in the created file.
5. Display the data in the file.
6. Stop the program.

PROGRAM:

import java.io.*;
import java.util.*;
class FileOperation
{
public static void main(String args[]) throws IOException
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter the name of the file to be created”);
String str=sc.nextLine();
File f=new File(str);
InputStream in = new FileInputStream(“D:\\student.txt”);
OutputStream out=new FileOutputStream(f);
DataInputStream dis = new DataInputStream(in);
DataOutputStream dos=new DataOutputStream(out);
String filename=f.getPath();
System.out.println(“Name of the created file:”+filename);
String path=f.getAbsolutePath();
System.out.println(“Path of the created file:”+path);
int count = in.available();
System.out.println(“Size of the data in file:”+count);
byte[] data = new byte[count];
System.out.println(“Copying the datas to the file :”+f+”.txt”);
dis.read(data);
System.out.println(“Data in the file: “+filename);
for(int i=0;i<count;i++)
{
char k=(char)data[i];
out.write(data[i]);
System.out.print(k+””);
}
}
}

32
OUTPUT:

RESULT:

Thus the java program to implement the different file operations was executed successfully.
EX. NO:9 GENERIC METHOD
DATE :

AIM:

To write a java program for finding the maximum value from the given integer and float array using a generic
method.

ALGORITHM:

1. Start the program.


2. Integer values are stored in an array.
3. Find maximum value of give n array.
4. Float values are stored in an array.
5. Find maximum value of the given array.
6. Stop the program.

PROGRAM:

import java.lang.*;
import java.util.*;
class Maximum
{
public static <E extends Comparable<E>> E max(E[] list)
{
E max = list[0];
for (int i = 1; i < list. length; i++)
{
if (list[i].compareTo(max)>0)
{
max = list[i];
}
}
return max;
}
}
class GenericExample
{
public static void main (String args[])
{
Integer arr1[] = {10, 15,45,34,75,25,89,64,72,5};
String str=arr1.toString();
System.out.println("\nElements in the integer array:\n");
for(int i=0;i<10;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println("\nMaximum: "+Maximum.max(arr1));
Float arr2[] = {1.1f, 25.3f,3.1f,5.5f,13.7f,8.4f,15.6f,46.5f,76.5f,34.9f};
System.out.println("\nElements in the float array:\n");
for(int j=0;j<10;j++)
{
System.out.print(arr2[j]+" ");
}
System.out.println("\n\nMaximum: "+Maximum.max(arr2));
}
}

34
OUTPUT:

RESULT:

Thus the java program for finding the maximum value from the given integer and float array using a generic
method was implemented successfully.
EX. NO:10 JAVAFX CONTROLS
DATE :

AIM:

To develop applications using JavaFX controls, layouts and menus

ALGORITHM:

1. Start the program.


2. Menu(): creates an empty menu
3. Menu(String s): creates a menu with a string as its label
4. Menu(String s, Node n):Constructs a Menu and sets the display text with the specified text and sets the
graphic Node to the given node.
5. Menu(String s, Node n, MenuItem… i):Constructs a Menu and sets the display text with the specified text, the
graphic Node to the given node, and inserts the given items into the items list.
6. Stop the program.

PROGRAM:

package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);

36
primaryStage.show();

}
}

OUTPUT:

RESULT:

Thus the menu application created successfully using JavaFX controls, layouts and menus.
EX. NO:11.a MINI PROJECT - OPAC SYSTEM
DATE :

AIM:

To develop a mini project OPAC system for library using Java concepts.

ALGORITHM:

1. Import the awt,swing packages.


2. Extend the JFrame which implements actionlistener to the class datas.
3. Create the textfield for id, name and button for next, address and the panel.
4. Create object for the getcontentpane().
5. Assign the length and breadth value for the layout using gridlayout.
6. Add the new labels for ISBN and book name.
7. Add the new button for the nextbook
8. Create the bookname under the driver jdbc odbc driver in the try block.
9. Create the object for exception as e and use it for catching the error.
10. Show all the records using showrecord.
PROGRAM:

//File Name should be Data.java

import java.sql.*; import


java.awt.*; import
java.awt.event.*;import
javax.swing.*;

public class Data extends JFrame implements ActionListener


{
JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res; static
Connection conn;static
Statement stat;

public Data()
{
super("My Application"); Container c =
getContentPane(); c.setLayout(new
GridLayout(5,1));

id = new JTextField(20); name =


new JTextField(20);
next = new JButton("Next BOOK");
p = new JPanel();

c.add(new JLabel("ISBN Number",JLabel.CENTER));c.add(id);


c.add(new JLabel("Book Name",JLabel.CENTER));
c.add(name);
c.add(p);

p.add(next);
next.addActionListener(this);pack();
setVisible(true); addWindowListener(new
WIN());
}
38
public static void main(String args[])
{
Data d = new Data();try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn =
DriverManager.getConnection("jdbc:odbc:stu");
// cust is the DSN Name
stat = conn.createStatement();
res = stat.executeQuery("Select * from stu"); // stu is the table nameres.next();
}
catch(Exception e)
{
System.out.println("Error" +e);
}
d.showRecord(res);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == next)
{
try
{
res.next();
}
catch(Exception e)
{
}
showRecord(res);
}
}
public void showRecord(ResultSet res)
{
try
{
id.setText(res.getString(2));
name.setText(res.getString(3));
}
catch(Exception e)
{
}
}//end of the main

//Inner class WIN implemented class WIN


extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Thank you","My
Application",JOptionPane.QUESTION_MESSAGE);
}
}
}

39
NOTE:
Create a new Database

1. Create a new Database file in MS ACCESS (our backend) named “books.mdb”.


2. Then create a table named “stu” in it.
3. The table stu contains the following fields and data types
i. ISBN - Text
ii. BookName - Text
4. Enter various records as you wish.
5. Save the database file.
Next step is to add our “books.mdb” to the System DSN. To do that follows the proceduregiven below,

i. Go to Start-> Control Panel -> Administrative tools.


ii. In that double click “Data Sources (ODBC)”.
iii. ODBC Data Source Administrator dialog appears.
iv. In that select “System DSN” tab and click the Add Button.
v. Select “Microsoft Access Driver(*.mdb)” and click Finish.
vi. ODBC Microsoft Access Setup appears. In the “Data Source name” type “stu”.
vii. Click on the “Select” button and choose your database file. Then click ok.Now your

database file gets added to the System DSN.

Table: Design View


Table Name: stu

Administrative Tools.
ODBC Data Source Administrator

Creating Microsoft Access Driver(*.mdb)


ODBC Microsoft Access Setup

OUTPUT:

To Compile:
javac Data.java
To Run:
java Data
RESULT:

Thus the program to develop the simple OPAC for the libraries is executedsuccessfully.
EX. NO:11.b MINI PROJECT
DATE :

ALGORITHM:

1. Open Android Studio and then click on File-> New -> New project.
2. Create a new Android application project with an application name: "Calculator" and package name:
"comjavahelps.calculator".
3. By default, Android uses a green Android robot icon. In this project, we are going to use a custom application
icon.
4. Right click on the "mipmap" folder and select New~ Image Asset
5. Replace the content of the activity_main.xml file by the following code. This code creates a TextView as the
calculator number screen and some necessary buttons. TextView is used instead of EditText, in order to
prevent manual user input using the default keypad of Android.
6. Right click on the "drawable"folder and select New Drawable resource file.
7. This drawable resource is used to decorate the buttons of the calculator. There are two gradient shapes in this
code; one is for button pressed state and another for the normal state.
8. For all the buttons in the activiy_main.xml, add a property "android:background".
9. Modify the MainActivity java as provided below. Complete description of the code is provided in comments.
10. Save all the changes and run the application.

Designing layout for the Android Application:

1. Click on app -> res -> layout -> activity_main.xml.


2. Now click on Design.

Code for MainActivity java:

package com.example.calculator

import androidx.appcompat.app.AppCompatActivity:

import android.os.Bundle;
import android.view. View;
import android.widget.Button;
import android.widget. TextView;

public class MainActivity extends AppCompatActivity (


Button button0;
Button buttonl;
Button button2;
Button button3;
Button button4;
Button buttons;
Button buttonó;
Button button7;
Button button8;
Button button9;
Button buttonAdd;
Button buttonSubstract;
Button buttonMul;
Button buttonDiv;
Button buttonClear,
Button buttonEqual;
String result;

45
String operator;
TextView result Text View;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControl0:
initControlListener():

private void initControlListener)


{
button0.setOnClickListener(new View.OnClickListener) [
@Override
public void onClick(View v) I
onNumberButtonClicked("0");
}
}
buttonl.setOnClickListener(new View.OnClickListener) {
@Override
public void onClick(View v) {
onNumberButtonClicked("1");

button2.setOnClickListener(new View.OnClickListener){ @Override


public void onClick(View v)
onNumberButtonClicked("2");

button3.setOnClickListener(new View.OnClickListener() @Override


public void onClick(View v)
onNumberButtonClicked("3");

button4.setOnClickListener(new View.OnClickListener) @Override


public void onClick(View v) {
onNumberButtonClicked("4");

button5.setOnClickListener(new View.OnClickListener() @Override


public void onClick(View v) {
onNumberButtonClicked("5");

buttonó.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onNumberButtonClicked("6");

button7.setOnClickListener(new View.OnClickListener(){ @Override


public void onClick(View v)(
onNumberButonClicked("7");

button8.setOnClickListener(new View.OnClickListener() @Override


public void onClick(View v)
onNumberButtonClicked("8");

button9.setOnClickListener(new View.OnClickListener) {
@Override
public void onClick(View v){
onNumberButtonClicked("9");

buttonClear.setOnClickListener(new View.OnClickListener) {
@Override
public void onClick(View v) {
onClearButtonClicked):

buttonSubstract.setOnClickListener(new View.OnClickListener() @Override


public void onClick(View v){
46
onOperatorButtonClicked("-");

buttonAdd.setOnClickListener(new View.OnClickListener) {
@Override
public void onClick(View v) {
onOperatorButtonClicked("+"):
buttonMul.setOnClickListener(new View.OnClickListener() @Override
public void onClick(View v) {
onOperatorButtonClicked("X");
buttonDiv.setOnClickListener(new View.OnClickListener) {
@Override
public void onClick(View v) {
onOperatorButtonClicked("/");

buttonEqual.setOnClickListener(new View.OnClickListener(0 @Override


public void onClick(View v) (
onEqualButtonClickedo:

private void onEqualButtonClicked()


int res = 0;
tryi
int number = Integer. valueOf{tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString);
switch (operator)
case +
res = number + number2;
break;
"T": case res = number/ number2;
break;
case ""
res = number number2;
break;
case "X":
res = number * number2;
break;
result = String.valueOf(res);
resultTextView.setText(result);
catch (Exception e)
e.printStack Trace();
private void onOperatorB uttonClicked(String operator) {
tmp = resultText View.getText().toString0:

onClearButtonClicked);
this.operator = operator;

private void onClearButtonClicked()0 result = ""


resultTextView.setText(");

private void onNumberButtonClicked(String pos)


result = result Text View.getText).toString);
result = result + pos;
resultText View.setT'ext(result);

private void initControl) [


button0 = (Button)findViewByld(R.id.button0):
buttonl = (Button)findViewByld(R.id.buttonl);
button2 = (Button)findViewByld(R.id.button2);
button3 = (Button)find ViewByld(R.id.button3);
buttond = (Button)find ViewByld(R.id.button4); button5 = (Button)findViewByld(R.id.button5);
button6 = (Button)find ViewByld(R.id.button6): button7 = (Button)find ViewByld(R.id.button7) buton8 =
(Button)findViewByld(R.id.button8)
button9 = (Button)find ViewByld(R. id. button9);
buttonAdd = (Button)findViewByld(R.id.buttonAdd);
buttonClear = (Button)find ViewByld(R.id.buttonClear); buttonSubstract = (Button)find View Byld(R.id.buttonSub);
buttonMul = (Button)findViewByld(R.id.buttonMul);
47
buttonDiv = (Button)findViewByld(R.id.buttonDiv);
buttonEqual = (Button)find ViewByld(R.id.buttonEqual);
resultTextView = (TextView find ViewByld(R.id.text_view_result:

Code for AndroidMainfest.xml:

<?xml version="1.0" encoding="utf-8"?>


<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_widthE match_parent" android:layout_height= wrap_content"

android:id="@+id/textview_result"
android:textSize="60sp"
android:textAlignment="viewEnd"/>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonl"
android:text="|"
android:layout_weight="|"
android:textSize="20sp"/>
<Button
android:id="@+id/button2"
android:text="2"
android:layout_weight="|"
android:textSize="20sp"/>
<Button
android:id="@+id/button3"
android:text="3"
android:layout weight="1"
android:textSize="20sp"/>
<Button
android:id="@+id/buttonAdd"
android:text="+"
android:layout weight="I" android:textSize="20sp"/>
<TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"-
<Button
android:id="@+id/button4"
andro "4"
android:layout_weight="I"
android:textSize="20sp"/>
<Button
android:id="@+id/buttons"
android:text="5"
android:layout_weight="1"
android:textSize="20sp"/>
<Button
android:id="@+id/button6"
android:text="6"
android: layout_weight="|" android:textSize="20sp"/>
<Button
android:id="@+id/buttonSub"
android:text="-"
android:layout_weight="1"
android:textSize="20sp">

48
<TableRow>
<TableRow
android:layout_width="match _parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button7"
android:text="7"
android:layout_weight="T"
android:textSize="20sp"/>
<Button
android:id="@+id/button8"
android:text="8"
android:layout_weight="|"
android:textSize="20sp"/>
<Button
android:id="@+id/button9"
android:text="9"
android:layout_weight="1"
android:textSize="20sp"/>
<Button
android:id="@+idbuttonMul"
android:text="*"
android:layout weight="|"
android:textSize="20sp"/>
TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonClear"
android:text="CLEAR"
android:layout weight="|"
android:textSize="20sp"/>
<Button
android:id="@+id/button0"
android:text="0"
android:layout weight="|"
android:textSize="20sp"/>
<Button
android:id="@+id/buttonEqual"
android:text="="
android:layout weight="T" android:textSize="20sp"/>
<Button
android:id="@+id/buttonDiv"
android:text="/"
android:layout_weight="|"
android:textSize="20sp"/> <TableRow>
STablelayout>

49

You might also like