Cs3364 Object Oriented Programming Laboratory Manual
Cs3364 Object Oriented Programming Laboratory Manual
LAB MANUAL
(REGULATION - 2023)
THIRD SEMESTER
1
TABLE OF CONTENTS
E.NO EXPERIMENT NAME Pg. No.
a PEO,PO,PSO 03-05
b Syllabus with CO 06
d Mode of Assessment 08
2
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
1. To afford the necessary background in the field of Information Technology to deal with engineering
problems to excel as engineering professionals in industries.
2. To improve the qualities like creativity, leadership, teamwork and skill thus contributing towards the
growth and development of society.
3. To develop ability among students towards innovation and entrepreneurship that caters to the needs of
Industry and society.
4. To inculcate and attitude for life-long learning process through the use of information technology sources.
5. To prepare then to be innovative and ethical leaders, both in their chosen profession and in other activities.
3
understanding of the limitations.
6 The engineer and society Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal, and cultural issues and the
consequent responsibilities relevant to the professional
engineering practice
7 Environment and Understand the impact of the professional engineering solutions
sustainability in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8 Ethics Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice
9 Individual and team work Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings
10 Communication Communicate effectively on complex engineering activities with
the engineering community and with the society at large, such
as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and
give and receive clear instructions
11 Project management and Demonstrate knowledge and understanding of the engineering
finance and management principles and apply these to one’s own work,
as a member and leader in a team, to manage projects and in
multidisciplinary environments
12 Life-long learning Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest
context of technological change
4
PROGRAM SPECIFIC OUTCOMES (PSOs)
By the completion of Information Technology program the student will have following Program specific
outcomes
1. Design secured database applications involving planning, development and maintenance using
state of theart methodologies based on ethical values.
2. Design and develop solutions for modern business environments coherent with the advanced
technologiesand tools.
3. Design, plan and setting up the network that is helpful for contemporary business environments
usinglatest hardware components.
4. Planning and defining test activities by preparing test cases that can predict and correct errors
ensuring asocially transformed product catering all technological needs.
5
CS3364 OBJECT ORIENTED PROGRAMMING LABORATORY LTPC
0 0 3 1.5
OBJECTIVES:
1. To build software development skills using java programming for real-world
applications.
2. To understand and apply the concepts of objects and classes.
3. To Bulid packages, interfaces, inheritance.
4. To implement exception handling and file processing.
5. 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 Swing and JavaFX controls, layouts and menus.
11. Develop a mini project for any application using Java concepts.
Operating Systems: Linux / Windows
Front End Tools: Eclipse IDE / Netbeans IDE TOTAL: 45 PERIODS
6
OUTCOMES:
At the end of the course, the student should be able to:
1. Design and develop java programs using object oriented programming concepts
2. Develop simple applications using object oriented concepts such as package, exceptions
3. Implement multithreading, and generics concepts
4. Create GUIs and event driven programming applications for real world problems
5. Implement and deploy web applications using Java
CO – PO – PSO Mapping
PO PSO
CO
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4
1 3 - - - 2 - - - - - - - 3 2 - -
2 2 2 - - - - - - - - - - 3 2 - -
3 2 2 - - - - - - - - - - 3 - - -
4 3 - - - - - - - - - - - 3 2 - -
5 3 3 3 - 2 - - - - - - - 3 2 - -
Avg 2.6 2.3 3.0 2.0 - - - - - - - 3.0 2.0 - -
7
MODE OF ASSESSMENT
2. Observation 20
5. Viva 20
Total 100
2. Record 10
3. Model Test 15
Total 50
8
INTRODUCTION / DESCRIPTION OF MAJOR SOFTWARE USED
JAVA:
Java is a programming language and computing platform first released by Sun Microsystems in
1995. There are lots of applications and websites that will not work unless you have Java installed,
and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters ,
game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere. Java
is free to download.
The latest Java version contains important enhancements to improve performance, stability and
security of the Java applications that run on your machine. Installing this free update will ensure
that your Java applications continue to run safely and efficiently.
The Java Runtime Environment (JRE) is what you get when you download Java software. The JRE
consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java
platform libraries. The JRE is the runtime portion of Java software, which is all you need to run it
in your Web browser.
The Java Plug-in software is a component of the Java Runtime Environment (JRE). The JRE allows
applets written in the Java programming language to run inside various browsers. The Java Plug-
in software is not a standalone program and cannot be installed separately.
The Java Virtual Machine is only one aspect of Java software that is involved in web interaction.
The Java Virtual Machine is built right into your Java software download, and helps run Java
applications.
In the Java programming language, all source code is first written in plain text files ending with
the .java extension. Those source files are then compiled into .class files by the javac compiler.
A .class file does not contain code that is native to your processor; it instead contains bytecodes —
the machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs
your application with an instance of the Java Virtual Machine.
Because the Java VM is available on many different operating systems, the same .class files are
capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS), Linux,
or Mac OS. Some virtual machines, such as the Java SE HotSpot at a Glance, perform additional
steps at runtime to give your application a performance boost. This includes various tasks such as
9
finding performance bottlenecks and recompiling (to native code) frequently used sections of code.
Through the Java VM, the same application is capable of running on multiple platforms.
A platform is the hardware or software environment in which a program runs. We've already
mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and
Mac OS. Most platforms can be described as a combination of the operating system and underlying
hardware. The Java platform differs from most other platforms in that it's a software-only platform
that runs on top of other hardware-based platforms.
Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based
platforms.
The API is a large collection of ready-made software components that provide many useful
capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known
as packages.
The API and Java Virtual Machine insulate the program from the underlying hardware.
As a platform-independent environment, the Java platform can be a bit slower than native code.
However, advances in compiler and virtual machine technologies are bringing performance close
to that of native code without threatening portability.
10
Key advantages of Java Programming
Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based
on the Object model.
Platform Independent − Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
11
EX.NO.:1(a)
SEQUENTIAL SEARCH
DATE:
AIM:
To develop a Java application to search an element in an array using sequential search
algorithm.
ALGORITHM:
PROGRAM:
LinearSearch.java
public class LinearSearch
{
static intsearch(intarr[], int n, int s)
{
for (inti = 0; i< n; i++)
{
if (arr[i] == s)
return i;
}
return -1;
}
public static void main(String[] args)
{
int[] arr = { 3, 4, 1, 7, 5 };
int n = arr.length;
int s = 4;
int index = search(arr, n, s);
if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at index " + index);
}
}
12
OUTPUT:
D:\Java>javac LinearSearch.java
D:\Java>java LinearSearch
RESULT:
Thus, the Java application to perform sequential search was implemented and
executed successfully.
13
EX.NO.:1(b)
BINARY SEARCH
DATE:
AIM:
To develop a Java application to search an element in an array using binary search
algorithm.
ALGORITHM:
PROGRAM:
BinarySearch.java
class BinarySearch
{
public static intbinarySearch(intarr[], int first, int last, int key)
{
if (last>=first)
{
int mid = (first +last)/2;
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] >key)
{
return binarySearch(arr, first, mid-1, key);
}
else
{
return binarySearch(arr, mid+1, last, key);
}
}
14
return -1;
}
public static void main(String args[])
{
intarr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
int result = binarySearch(arr,0,last,key);
if (result == -1)
System.out.println("Element is not found!");
else
System.out.println("Element is found at index: "+result);
}
}
OUTPUT:
D:\Java>javac BinarySearch.java
D:\Java>java BinarySearch
Element is found at index: 2
D:\Java>
RESULT:
Thus, the Java application to perform binary search was implemented and executed
successfully.
15
EX.NO.:1(c)
INSERTION SORT
DATE:
AIM:
To develop a Java application to sort an array of elements in ascending order using
insertion sort.
ALGORITHM:
PROGRAM:
InsertionSort.java
16
{
num[j+1]=num[j];
}
else
{
break;
}
j=j-1;
}
num[j+1]=x;
}
System.out.print("\n\nArray after Insertion Sort\n");
for(i=0; i<num.length; i++)
{
System.out.print(num[i]+" ");
}
}
}
OUTPUT:
D:\Java>javac InsertionSort.java
D:\Java>java InsertionSort
Array before Insertion Sort
12 9 37 86 2 17 5
Array after Insertion Sort
2 5 9 12 17 37 86
D:\Java>
RESULT:
Thus, the Java application to sort an array of N elements using insertion sort was
implemented and executed successfully.
17
EX.NO.:1(d)
SELECTION SORT
DATE:
AIM:
To develop a Java application to sort an array of elements in ascending order using
selectin sort.
ALGORITHM:
PROGRAM:
SelectionSort.java
18
int temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
public static void main(String[] args)
{
int[] arr= {15,21,6,3,19,20};
System.out.println("Elements in the array before Sorting");
for(int i:arr)
System.out.print(i+" ");
selectionsort(arr);
System.out.println("\nElements in the array after Sorting");
for(int i:arr)
System.out.print(i+" ");
}
}
OUTPUT:
D:\Java>javac SelectionSort.java
D:\Java>java SelectionSort
Elements in the array before Sorting
15 21 6 3 19 20
Elements in the array after Sorting
3 6 15 19 20 21
D:\Java>
RESULT:
Thus, the Java application to sort an array of N elements using selection sort was
implemented and executed successfully.
19
EX.NO.: 2(a)
STACK DATA STRUCTURE
DATE:
AIM:
To develop a Java program to implement stack data structure using classes and
objects.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class named Stack and declare the instance variables st[], top,
maxsize as private.
Step3:Use constructor to allocate memory space for the array and initialize top as -1.
Step 4: Define methods such as isFull(), isEmpty(), push(), pop() and printStack();
Step 5: Push Operation
Step 5.1: Check whetherstack has some space or stack is full.
Step 5.2: If the stack has no space then display “overflow” and exit.
Step 5.3: If the stack has space then increase top by 1 to point next empty space.
Step 5.4: Add element to the new stack location, where top is pointing.
Step 5.5: Push operation performed successfully.
Step 6: Pop operation
Step 6.1: Check whether stack has some element or stack is empty.
Step 6.2: If the stack has no element means it is empty then display “underflow”
Step 6.3: If the stack has some element, accesses the data element at which top is
pointing.
Step 6.4: Decrease the value of top by 1.
Step 6.5: Pop operation performed successfully.
Step 7: PrintStack operation
Step 7.1:Check whether stack has some element or stack is empty.
Step 7.2: If the stack has no element means it is empty then display “underflow”.
Step 7.3: If the stack has some element, traverse the array from top to bottom and
display the elements.
Step 8: Define the main() method
Step 9: Create object of Stack class.
Step 10: Display the menu and get the user choice and invoke appropriate method.
Step 11: Stop the program.
20
PROGRAM:
Stack.java
import java.util.Scanner;
public class Stack
{
private intmaxsize, top;
private int[] st;
public Stack(int size)
{
maxsize = size;
st = new int[maxsize];
top = -1;
}
booleanisEmpty()
{
return top==-1;
}
booleanisFull()
{
return top==maxsize-1;
}
public void push(int element)
{
if(isFull())
System.out.println("Overflow");
else
st[++top] = element;
}
public intpop()
{
if(isEmpty())
{
System.out.println("UnderFlow");
return (-1);
}
return (st[top--]);
}
public void printStack()
{
System.out.println("Stack Elements:");
for (inti = top; i>=0; i--)
21
System.out.println(st[i]);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter stack size");
int size=sc.nextInt();
Stack obj = new Stack(size);
while (true)
{
System.out.println("\nSTACK\n*****\n1.PUSH\n2.POP
\n3.Display\n4.EXIT\nEnter your choice");
intch = sc.nextInt();
switch (ch)
{
case 1:
System.out.println("Enter Element");
int n = sc.nextInt();
obj.push(n);
break;
case 2:
System.out.printf("Poped element is %d", obj.pop());
break;
case 3:
obj.printStack();
break;
case 4:
System.exit(0);
default:
System.out.println("Wrong option");
}
}
}
}
OUTPUT:
D:\Java>javac Stack.java
D:\Java>java Stack
Enter stack size
5
STACK
*****
1.PUSH
1. POP
22
2.Display
4.EXIT
Enter your choice
1
Enter Element
12
STACK
*****
1.PUSH
1. POP
2.Display
4.EXIT
Enter your choice
1
Enter Element
34
STACK
*****
1.PUSH
1. POP
2.Display
4.EXIT
Enter your choice
1
Enter Element
56
STACK
*****
1.PUSH
1. POP
2.Display
4.EXIT
Enter your choice
1
Enter Element
78
STACK
*****
1.PUSH
1. POP
2.Display
4.EXIT
Enter your choice
3
Stack Elements:
78
23
56
34
12
STACK
*****
1.PUSH
1. POP
2.Display
4.EXIT
Enter your choice
2
Poped element is 78
STACK
*****
1.PUSH
1.POP
2.Display
4.EXIT
Enter your choice
3
Stack Elements:
56
34
12
STACK
*****
1.PUSH
3.POP
4.Display
4.EXIT
Enter your choice
4
D:\Java>
RESULT:
Thus, the Java program to implement stack data structure using classes and objects
has developed and executed successfully.
24
EX.NO.: 2(b)
QUEUE DATA STRUCTURE
DATE:
AIM:
To develop a Java program to implement queue data structure using classes and
objects.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class named Queue and declare the instance variables items[], front, rear,
maxsize as private.
Step3:Use constructor to allocate memory space for the array and initialize front as -1 and
rear as -1.
Step 4: Define methods such as isFull(), isEmpty(), enQueue(), deQueue() and display();
Step 5: Enqueue Operation
Step 5.1: Check whetherqueue has some space or queue is full.
Step 5.2: If the queue has no space then display “overflow” and exit.
Step 5.3: If the queue has space then increase rear by 1 to point next empty space.
Step 5.4: Add element to the new location, where rear is pointing.
Step 5.5: Enqueue operation performed successfully.
Step 6: Dequeue operation
Step 6.1: Check whether queue has some element or queue is empty.
Step 6.2: If the queue has no element means it is empty then display “underflow”
Step 6.3: If the queue has some element, accesses the data element at which front is
pointing.
Step 6.4: Incrementthe value of front by 1.
Step 6.5:Dequeue operation performed successfully.
Step 7: Displayoperation
Step 7.1:Check whether queue has some element or queue is empty.
Step 7.2: If the stack has no element means it is empty then display “underflow”.
Step 7.3: If the stack has some element, traverse the array from front to rear and
display the elements.
Step 8: Define the main() method
Step 9: Create object of Queue class.
Step 10: Display the menu and get the user choice and invoke appropriate method.
Step 11: Stop the program.
25
PROGRAM:
Queue.java
import java.util.Scanner;
public class Queue
{
private intitems[];
private intmaxsize, front, rear;
Queue(int size)
{
maxsize=size;
items = new int[size];
front = -1;
rear = -1;
}
booleanisFull()
{
if (front == 0 && rear ==maxsize-1)
{
return true;
}
return false;
}
booleanisEmpty()
{
if (front == -1)
return true;
else
return false;
}
26
{
System.out.println("Queue is full");
}
else
{
if (front == -1)
front = 0;
rear++;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
intdeQueue()
{
int element;
if (isEmpty())
{
System.out.println("Queue is empty");
return (-1);
}
else
{
element = items[front];
if (front >= rear)
{
front = -1;
rear = -1;
}
else
{
front++;
}
return (element);
}
27
}
void display()
{
inti;
if (isEmpty())
{
System.out.println("Empty Queue");
}
else
{
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i<= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
28
break;
case 2:
System.out.printf("Dequeued element is %d",
obj.deQueue());
break;
case 3:
obj.display();
break;
case 4:
System.exit(0);
default:
System.out.println("Wrong option");
}
}
}
}
OUTPUT:
D:\Java>javac Queue.java
D:\Java>java Queue
Enter queue size
5
QUEUE
*****
1.ENQUEUE
1. DEQUEUE
2. DISPLAY
3. EXIT
Enter your choice
1
Enter Element
12
Inserted 12
QUEUE
*****
1.ENQUEUE
1. DEQUEUE
2. DISPLAY
3. EXIT
Enter your choice
29
Enter Element
34
Inserted 34
QUEUE
*****
1.ENQUEUE
1. DEQUEUE
2. DISPLAY
3. EXIT
Enter your choice
1
Enter Element
56
Inserted 56
QUEUE
*****
1.ENQUEUE
1. DEQUEUE
2. DISPLAY
3. EXIT
Enter your choice
1
Enter Element
78
Inserted 78
QUEUE
*****
1.ENQUEUE
1. DEQUEUE
2. DISPLAY
3. EXIT
Enter your choice
3
Front index-> 0
Items ->
12 34 56 78
Rear index-> 3
QUEUE
*****
1.ENQUEUE
1. DEQUEUE
2. DISPLAY
3. EXIT
Enter your choice
30
2
Poped element is 12
QUEUE
*****
1.ENQUEUE
4. DEQUEUE
5. DISPLAY
6. EXIT
Enter your choice
3
Front index-> 1
Items ->
34 56 78
Rear index-> 3
QUEUE
*****
1.ENQUEUE
7. DEQUEUE
8. DISPLAY
9. EXIT
Enter your choice
4
D:\Java>
RESULT:
Thus, the Java program to implement queue data structure using classes and objects
has developed and executed successfully.
31
EX.NO.: 3
PAYSLIP GENERATION USING INHERITANCE
DATE:
AIM:
To develop a java application to generate pay slip for different category of employees
using theconcept of inheritance.
ALGORITHM:
PROGRAM:
PaySlip.java
import java.util.Scanner;
class Employee
{
String Emp_name,Mail_id,Address,Emp_id, Mobile_no;
double BP,GP,NP,DA,HRA,PF,CF;
Scanner get = new Scanner(System.in);
Employee()
{
System.out.println("Enter Name of the Employee:");
Emp_name = get.nextLine();
32
System.out.println("Enter Address of the Employee:");
Address = get.nextLine();
System.out.println("Enter ID of the Employee:");
Emp_id = get.nextLine();
System.out.println("Enter Mobile Number:");
Mobile_no = get.nextLine();
System.out.println("Enter E-Mail ID of the Employee :");
Mail_id = get.nextLine();
}
void display()
{
System.out.println("Employee Name: "+Emp_name);
System.out.println("Employee Address: "+Address);
System.out.println("Employee ID: "+Emp_id);
System.out.println("Employee Mobile Number: "+Mobile_no);
System.out.println("Employee E-Mail ID"+Mail_id);
DA=BP*0.97;
HRA=BP*0.10;
PF=BP*0.12;
CF=BP*0.01;
GP=BP+DA+HRA;
NP=GP-PF-CF;
System.out.println("Basic Pay :"+BP);
System.out.println("Dearness Allowance : "+DA);
System.out.println("House Rent Allowance :"+HRA);
System.out.println("Provident Fund :"+PF);
System.out.println("Club Fund :"+CF);
33
System.out.println("Enter Basic pay of the Assistant Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Assistant
ProfessorPay Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class AssociateProfessor extends Employee
{
AssociateProfessor()
{
System.out.println("Enter Basic pay of the Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Associate
Professor Pay Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class Professor extends Employee
{
Professor()
{
System.out.println("Enter Basic pay of the Professor:");
BP = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Professor Pay
Slip"+"\n"+"=============================="+"\n");
super.display();
}
}
class Payslip
{
public static void main(String[] args)
{
char ans;
Scanner sc = new Scanner(System.in);
do
{
System.out.println("Main Menu");
System.out.println("1. Programmer \n2. Assistant Professor \n3. Associate
Professor \n4. Professor");
System.out.println("Enter your choice: ");
34
int choice=sc.nextInt();
switch(choice)
{
case 1:
Programmer p=new Programmer();
p.display();
break;
case 2:
AssistantProfessorap=new AssistantProfessor();
ap.display();
break;
case 3:
AssociateProfessor asp=new AssociateProfessor();
asp.display();
break;
case 4:
Professor PR=new Professor();
PR.display();
break;
}
OUTPUT:
Main Menu
10. Programmer
11. Assistant Professor
12. Associate Professor
13. Professor
Enter your choice:
1
Enter Name of the Employee:
Raja
Enter Address of the Employee:
Chennai
Enter ID of the Employee:
12345
Enter Mobile Number:
9876543210
Enter E-Mail ID of the Employee :
[email protected]
Enter Basic pay of the Programmer:
35
56000
==============================
Programmar Pay Slip
==============================
RESULT:
Thus, the Java application to generate pay slip for different category of employees
was implementedusing inheritance and the program was executed successfully.
36
EX.NO.:4
ABSTRACT CLASS IMPLEMENTATION
DATE:
AIM:
To write a Java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class.
ALGORITHM:
PROGRAM:
AbstractArea.java
import java.util.*;
abstract class Shape
{
inta,b;
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
System.out.println("\t\tCalculating Area of Rectangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter length: ");
a=input.nextInt();
System.out.print("\nEnter breadth: ");
37
b=input.nextInt();
int area=a*b;
System.out.println("Area of Rectangle: "+area);
}
}
class Triangle extends Shape
{
void printArea()
{
System.out.println("\t\tCalculating Area of Triangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter height: ");
a=input.nextInt();
System.out.println("\nEnter breadth: ");
b=input.nextInt();
double area=0.5*a*b;
System.out.println("Area of Triangle: "+area);
}
}
class Circle extends Shape
{
void printArea()
{
System.out.println("\t\tCalculating Area of Circle");
Scanner input=new Scanner(System.in);
System.out.print("Enter radius: ");
a=input.nextInt();
double area=3.14*a*a;
System.out.println("Area of Circle: "+area);
}
}
class AbstractArea
{
public static void main(String[] args)
{
Shape obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
}
38
OUTPUT:
Calculating Area of Rectangle
Enter length: 10
Enter breadth: 20
Area of Rectangle: 200
Calculating Area of Triangle
Enter height: 34
Enter breadth: 56
Area of Triangle: 952.0
Calculating Area of Circle
Enter radius: 23
Area of Circle: 1661.06
RESULT:
Thus,the Java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class wasdeveloped and executed successfully.
39
EX.NO.: 5
INTERFACE
DATE:
AIM:
To write a Java program to calculate the area of rectangle, circle and triangle by
implementing the interface shape.
ALGORITHM:
PROGRAM:
TestArea.java
import java.util.Scanner;
interface Shape
{
public void printArea();
}
class Rectangle implements Shape
{
public void printArea()
{
System.out.println("\t\tCalculating Area of Rectangle");
Scanner input=new Scanner(System.in);
System.out.print("Enter length: ");
int a=input.nextInt();
System.out.print("\nEnter breadth: ");
int b=input.nextInt();
int area=a*b;
System.out.println("Area of Rectangle: "+area);
}
}
class Triangle implements Shape
{
public void printArea()
40
{
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();
}
}
41
OUTPUT:
D:\Java>javac TestArea.java
D:\Java>java TestArea
Calculating Area of Rectangle
Enter length: 14
Enter breadth: 24
Area of Rectangle: 336
Calculating Area of Triangle
Enter height: 45
Enter breadth: 32
Area of Triangle: 720.0
Calculating Area of Circle
Enter radius: 5
Area of Circle: 78.5
D:\Java>
RESULT:
Thus, the Java program to calculate the area of rectangle, circle and triangle using the
concept of interfacewasdeveloped and executed successfully.
42
EX.NO.:6
USER DEFINED EXCEPTION HANDLING
DATE:
AIM:
To write a Java program to implement user defined exception handling.
ALGORITHM:
PROGRAM:
UserDefinedException.java
import java.util.*;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
43
class BankAccount
{
private double balance;
private intaccountNumber;
public BankAccount(intaccountNumber,doubleinitialBalance)throws
NegativeAmtException
{
if(initialBalance<0)
throw new NegativeAmtException("Initial amount should not be
negative!");
balance = initialBalance;
this.accountNumber = accountNumber;
}
public void deposit(double amount)throws NegativeAmtException
{
if (amount < 0)
{
throw new NegativeAmtException("Don't deposit negative amount!");
}
balance = balance + amount;
System.out.println("Amount deposited");
System.out.println("Balance amount : "+getBalance());
}
public void withdraw(double amount)throws NegativeAmtException
{
if (amount < 0)
{
throw new NegativeAmtException("Don't withdraw a negative
amount!");
}
else if(amount<=balance)
{
balance = balance – amount;
}
else
{
System.out.println("Insufficient amount");
}
44
return "Account Number :" + accountNumber + " Balance :" + balance;
}
}
public class UserDefinedException
{
public static void main(String[] args)
{
intch,amt;
Scanner sc=new Scanner(System.in);
System.out.print("Enter Account Number:");
int a=sc.nextInt();
System.out.print("Enter the initial Amount:");
int b=sc.nextInt();
BankAccount ac;
try
{
ac=new BankAccount(a,b);
while(true)
{
System.out.println("Main Menu");
System.out.println("1.Deposit \n2.Withdraw \n3.Check Balance
\n4.Display \n5.Exit");
System.out.print("Enter your Choice: ");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.print("Enter the amount to
deposit:");
amt=sc.nextInt();
ac.deposit(amt);
break;
case 2:
System.out.print("Enter the amount to
Withdraw:");
amt=sc.nextInt();
ac.withdraw(amt);
break;
case 3:
System.out.println("Balance amount :
"+ac.getBalance());
break;
case 4:
System.out.println("Your account
details\n"+ac);
break;
case 5:
sc.close();
System.exit(0);
45
default:
System.out.println("Invalid Choice");
}
}
}
catch(NegativeAmtException e)
{
System.out.println("Exception Caught : "+e);
}
}
}
OUTPUT:
Enter Account Number:1234
Enter the initial Amount:500
Main Menu
1.Deposit
2.Withdraw
3.Check Balance
4.Display
5.Exit
Enter your Choice: 1
Enter the amount to deposit:-456
Exception Caught : Don't deposit negative amount!
RESULT:
Thus the Java program to implement user defined exception handling was
implementedand executed successfully.
46
EX.NO.: 7
MULTITHREADING IMPLEMENTATION
DATE:
AIM:
To write a java program to implement a multi-threaded application.
ALGORITHM:
PROGRAM:
MultiThread.java
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: "
+ x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x)
{
47
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " +
x * x * x);
}
}
class A extends Thread
{
public void run()
{
intnum = 0;
Random r = new Random();
try
{
for (inti = 0; i< 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " +
num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public classMultiThread
{
public static void main(String[] args)
48
{
A a = new A();
a.start();
}
}
OUTPUT:
Main Thread and Generated Number is 33
New Thread 33 is ODD and Cube of 33 is: 35937
RESULT:
Thus, the java program to implement multithreaded application was executed
successfully.
49
EX.NO.: 8
FILE OPERATIONS
DATE:
AIM:
To write a java program to copy the contents of one file to another file using file
operations.
ALGORITHM:
PROGRAM:
FileCopy.java
import java.io.*;
class CopyFile
{
public static void main(String args[]) throws IOException
{
inti;
FileInputStream fin = null;
FileOutputStreamfout = null;
if(args.length != 2)
{
System.out.println("Usage: CopyFile from to");
return;
}
System.out.println("Displaying contents of "+ args[0]+"\n");
try
{
fin = new FileInputStream(args[0]);
50
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("Error Reading File");
}
finally
{
try
{
fin.close();
}
catch(IOException e)
{
System.out.println("Error Closing File");
}
}
System.out.println("\nCopying contents of "+ args[0] + "to " + args[1]+"\n");
try
{
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do
{
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("I/O Error: " + e);
}
finally
{
try
{
if(fin != null)
fin.close();
}
51
catch(IOException e2)
{
System.out.println("Error Closing Input File");
}
try
{
if(fout != null)
fout.close();
}
catch(IOException e2)
{
System.out.println("Error Closing Output File");
}
}
System.out.println("\nFile Copied\n");
System.out.println("\nDisplaying contents of "+ args[1]+"\n");
try
{
fin = new FileInputStream(args[1]);
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
}
catch(IOException e)
{
System.out.println("Error Reading File");
}
finally
{
try
{
fin.close();
}
catch(IOException e)
{
System.out.println("Error Closing File");
}
}
}
}
52
OUTPUT:
R:\oop>javac CopyFile.java
R:\oop>java CopyFile FIRST.txt SECOND.txt
File Copied
R:\oop>
RESULT:
Thus, the java program to copy the contents of one file to another file using file was
written, executed and verified.
53
EX.NO.: 9
GENERIC CLASS
DATE:
AIM:
To write a java program to find the maximum and minimum value from the given
type of elements using ageneric function.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class Myclass to implement generic class and generic methods.
Step 3: Get the set of the values belonging to specific data type.
Step 4:Create the objects of the class to hold integer, character and double values.
Step 5:Create the method to compare the values and find the maximum value stored in the
array.
Step 6: Invoke the method with integer, character, double and string values. The output will
be displayedbased on the data type passed to the method.
Step 7:Stop the program.
PROGRAM:
GenericsDemo.java
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] obj)
{
vals = obj;
}
public T min()
{
T v = vals[0];
for(inti=1; i<vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(inti=1; i<vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
54
}
}
class GenericsDemo
{
public static void main(String args[])
{
Integer num[]={10,2,5,4,6,1};
Character ch[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
String str[]= {"hai","how","are","you"};
MyClass<Integer>iob = new MyClass<Integer>(num);
MyClass<Character> cob = new MyClass<Character>(ch);
MyClass<Double>dob = new MyClass<Double>(d);
MyClass<String>sob=new MyClass<String>(str);
System.out.println("Max value in num: " + iob.max());
System.out.println("Min value in num: " + iob.min());
System.out.println("Max value in ch: " + cob.max());
System.out.println("Min value in ch: " + cob.min());
System.out.println("Max value in d: " + dob.max());
System.out.println("Min value in d: " + dob.min());
System.out.println("Max value in str: " + sob.max());
System.out.println("Min value in str: " + sob.min());
}
}
OUTPUT:
Max value in num: 10
Min value in num: 1
Max value in ch: v
Min value in ch: a
Max value in d: 88.3
Min value in d: 10.4
Max value in str: you
Min value in str: are
RESULT:
Thus, the Java program to find the maximum and minimum value from the given type
of elements was implemented using generics and executed successfully.
55
EX.NO.: 10(a)
MULTIPLE CHOICE TEST QUESTION IN JAVAFX
DATE:
AIM:
To write a program to display multiple choice test question using JavaFX.
ALGORITHM:
PROGRAM:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MCTest extends Application
{
@Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("Test Question 1");
Label labelfirst= new Label("What is 10 + 20?");
Label labelresponse= new Label();
Button button= new Button("Submit");
RadioButton radio1, radio2, radio3, radio4;
radio1=new RadioButton("10");
56
radio2= new RadioButton("20");
radio3= new RadioButton("30");
radio4= new RadioButton("40");
button.setDisable(true);
radio1.setOnAction(e ->button.setDisable(false) );
radio2.setOnAction(e ->button.setDisable(false) );
radio3.setOnAction(e ->button.setDisable(false) );
radio4.setOnAction(e ->button.setDisable(false) );
button.setOnAction(e ->
{
if (radio3.isSelected())
{
labelresponse.setText("Correct answer");
button.setDisable(true);
}
else
{
labelresponse.setText("Wrong answer");
button.setDisable(true);
}
});
57
RESULT:
Thus, the Java program for multiple choice test questions was implemented and executed
successfully.
58
EX.NO.: 10(b)
SIMPLE EDITOR USING JAVAFX
DATE:
AIM:
To write a program to create simple editor with menu using JavaFX.
ALGORITHM:
PROGRAM:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
public class MenuUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception
{
59
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);
60
primaryStage.setTitle("JavaFX Menu");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
OUTPUT:
RESULT:
Thus, the Java program for simple editor was implemented and executed successfully.
61
EX.NO.:11
DATE: MINI PROJECT
LIBRARY MANAGEMENT SYSTEM
AIM:
To write a program to create simple library management system that allows users to add,
view, and borrow books.
ALGORITHM
Step 1: Start
Step 2: Initialize Library
Create an empty list to store books.
Initialize a counter for book IDs.
Step 3: Main Menu
Display options: Add Book, View Books, Borrow Book, Exit.
Step 4: Get User Choice
Read the user's menu choice.
Step 5: Perform Action Based on Choice
If Add Book:
Prompt for book title and author.
Create a new book with a unique ID and add it to the library.
If View Books:
Display all books in the library with their details.
If Borrow Book:
Prompt for book ID.
Mark the book as borrowed if it's available.
If Exit:
Exit the program.
Step 6: Stop
PROGRAM:
import java.util.ArrayList;
import java.util.Scanner;
class Book {
int id;
String title;
String author;
boolean isBorrowed;
Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
this.isBorrowed = false;
}
}
public class LibraryManagementSystem {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<>();
62
Scanner scanner = new Scanner(System.in);
int bookIdCounter = 1;
while (true) {
System.out.println("Library Management System Menu:");
System.out.println("1. Add Book");
System.out.println("2. View Books");
System.out.println("3. Borrow Book");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
if (choice == 4) {
System.out.println("Exiting the program...");
break;
}
switch (choice) {
case 1:
System.out.print("Enter the book title: ");
String title = scanner.nextLine();
System.out.print("Enter the book author: ");
String author = scanner.nextLine();
library.add(new Book(bookIdCounter++, title, author));
System.out.println("Book added.");
break;
case 2:
System.out.println("Library Books:");
for (Book book : library) {
System.out.println("ID: " + book.id + ", Title: " + book.title + ", Author: " +
book.author + ", Borrowed: " + book.isBorrowed);
}
break;
case 3:
System.out.print("Enter the book ID to borrow: ");
int bookId = scanner.nextInt();
boolean found = false;
for (Book book : library) {
if (book.id == bookId) {
found = true;
if (!book.isBorrowed) {
book.isBorrowed = true;
System.out.println("You have borrowed \"" + book.title + "\".");
} else {
System.out.println("Sorry, the book is already borrowed.");
}
break;
}
}
if (!found) {
System.out.println("Book ID not found.");
}
break;
63
default:
System.out.println("Invalid choice. Please try again.");
break;
}
System.out.println();
}
scanner.close();
}
}
64
4. Run the JAR File:
Run the JAR file using the following command:
java -jar LibraryManagementSystem.jar
OUTPUT:
Library Management System Menu:
1. Add Book
2. View Books
3. Borrow Book
4. Exit
Enter your choice: 1
Enter the book title: Effective Java
Enter the book author: Joshua Bloch
Book added.
RESULT:
Thus, the Java program for simple library management was implemented and executed successfully.
66