Oops Lab Manual
Oops Lab Manual
SEMESTER:III REGULATION:2021
SUB CODE: CS3381 SUB NAME: OBJECT ORIENTED PROGRAMMING
Prepared By Approved By
Dr.I.Vallirathi, ASP/CSE
Approved on :
VISION
To enhance young professionals to compete the global challenges in the field of
computer science and engineering to pursue research in this field.
MISSIO N
To provide quality education to meet the need of the society.
Provide learning ambience to enhance innovations, problem solving skill,
leadership qualities, team spirit and ethical responsibility.
PEO
The graduates will be able to meet the need of the society.
The graduates will be able to design and establish software and to resolve
various technological problems.
The graduates will be able to develop professional skills which make ready
them for immediate employment and understand the need of lifelong
learning for a successful professional career.
PROGRAM OUTCOMES
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an 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 sustainability: Understand the impact of the professional engineer ing
solutions 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.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering 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 technologica l
change.
COURSE OBJECTIVES
T1. Herbert Schildt, ―Java The complete reference‖, 8th Edition, McGraw Hill Education, 2011.
T2. Cay S. Horstmann, Gary cornell, ―Core Java Volume –I Fundamentals‖, 9th Edition, Prentice
Hall, 2013.
COURSE OUTCO M ES:
[Cognitive Level K1- remember, K2- Understand, K3- Apply, K4 - Analyze, K5- Evaluate,
K6- Synthesize]
After successful completion of the course, the students should be able to
Highest
CO No. Course Outcomes
Cognitiv e
Level
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 SEQUENTIAL SEARCH, BINARY SEARCH, AND QUADRATIC
SORTING ALGORITHMS
Aim
SEQUENTIAL SEARCH
Algorithm:
Program :
import java.io.*;
public class LinearSearchExample{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
OUTPUT
Binary Search
Algorithm
Begin with the mid element of the whole array as a search key.
If the value of the search key is equal to the item then return an index of the search key.
Or if the value of the search key is less than the item in the middle of the interval, narrow the
interval to the lower half.
Otherwise, narrow it to the upper half.
Repeatedly check from the second point until the value is found or the interval is empty.
Program
import java.io.*;
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
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[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
OUTPUT
Selection Sort
Algorithm
1. finding the minimum value in the unsorted array and move it to the first position.
2. Now increase the pointer value by 1.
3. Again start searching for next minimal value in array (except in previous one)
4. If found minimal swap the value to second position element
5. Else leave it move pointer next
6. Sort the remaining values of data set (excluding the previous value).
Program
import java.io.*;
public class SelectionSortEx {
public static void main(String a[]) {
//Numbers which are to be sorted
int n[] = {
55,
33,
22,
88,
99,
44,
11,
77,
66
};
//Displays the numbers before sorting
System.out.print("Before sorting, numbers are ");
for (int i = 0; i < n.length; i++) {
System.out.print(n[i] + " ");
}
System.out.println();
//Sorting in ascending order using bubble sort
initializeselectionSort(n);
//Displaying the numbers after sorting
System.out.print("After sorting, numbers are ");
for (int i = 0; i < n.length; i++) {
System.out.print(n[i] + " ");
}
}
//This method sorts the input array in descending order
OUTPUT
Insertion sort
Algorithm
int n[] = {
124,
23,
43,
12,
177,
25,
2,
1,
67
};
System.out.println();
//Sorting in ascending order using bubble sort
initializeInsertionSort(n);
int j = i;
int B = n[i];
j--;
n[j] = B;
OUTPUT
Result:
Thus the java program to Solve problems by using sequential search, binary search,
and quadratic sorting algorithms was executed successfully.
Outcome:
Thus the student can know to implement sorting and searching algorithms using
java .
Viva-voce :
1.What does the default access specifier means ?
2.Can I import same package/class twice?
3. Do we need to import java.lang.package ?
4. What is the difference between public class and class ?
Aim
Write a java program to implement stack and queue data structures using classes and
objects.
QUEUE USING CLASSES AND OBJECT
Algorithm
Program
import java.util.*;
// define queue
class class Queue
{
int arr[], front, rear, cap, n1;
// Queue constructor
Queue(int n)
{
arr = new int[n]; cap = n;
front = 0;
rear = -1;
n = 0;
}
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.dequeue();
System.out.println("Front element is: " + q.peek());
q.dequeue();
q.dequeue();
if (q.isEmpty())
System.out.println("Queue Is Empty");
else
System.out.println("Queue Is Not Empty");
}
}
Output
STACK USING CLASSES AND OBJECT
ALGORITHM
Step1:Create a stack class
Step2:Get the stack upper limit from the user
Step3:Get the elements of the stack and perform push operation, increment the top pointer by 1,if
top exceeds the upper limit then display stack overflow
Step4:Perform pop operation(delete the element from the stack ),decrement the Top pointer by 1, if
top reaches zero then display stack underflow
PROGRAM
import java.io.*;
import java.util.*;
class stackimp
{
int stack[]=new int[20]; int no,ch,choice,cont; int ele,top=0;
Scanner sc=new Scanner(System.in);
void stackcheck()
{
stack[top]=ele; top++;
}
else
{
System.out.println("Stack overflow");
}
System.out.println("Do you want to
continue(1-Yes,2-No):"); ch=sc.nextInt();
}while(ch==1);
}
else if(choice==2)
{
do
{
if(top>0)
{
System.out.println(" the element popped from the stack is:"+stack[top-1]);
top--;
//System.out.println(top);
}
else
{
System.out.println("Stack underflow");
}
System.out.println("Do you want to continue(1-Yes,2-No):");
ch=sc.nextInt();
}while(ch==1);
}
System.out.println("Do you want to continue push or pop(1-Yes,2-No)");
cont=sc.nextInt();
}while(cont==1);
}
public static void main(String args[])
{
stackimp st=new stackimp();
st.stackcheck();
}
}
OUTPUT
Result
: Thus the java program to implement stack and queue data structures using classes
and
objects was executed successfully.
Outcome:
Thus the student can know to implement stack and Queue using java .
Viva Voce :
1. What is multithreading?
4. Define Constructor.
6.Define destructor.
7.Define class .
EX:NO : 3 EMPLOYEE PAY SLIP
AIM
To write a program to create an employee pay slip by using the inheritance concept in java.
ALGORITHM
Step1: Create employee class with employee name, id, address, mailid and phone number as
members.
Step2: Create programmer, assistant professor, associate professor, professor classes make the
classes inherit the employee class.
Step3: Get the basic pay from the user.
Step4: Calculate DA, HRA, PF, Staffclub amount where
DA=.97*Basic pay HRA=.10*Basic pay PF=.12*Basic pay
Staff club amount=.001*Basic pay
PROGRAM
import java.io.*;
import
java.util.*; class
employee
{
String emp_name; int emp_id;
String emp_address; String emp_mailid; int emp_phone;
int des; double NET; double BP; double DA; double HRA; double PF; double SC;
Scanner sc=new
Scanner(System.in); void
getdetails()
{
System.out.println("Enter the Employee Name:"); emp_name=sc.next();
System.out.println("Enter the Employee ID:");
emp_id=sc.nextInt();
System.out.println("Enter the Employee Address:");
emp_address=sc.next();
System.out.println("Enter the Employee Mail-ID:"); emp_mailid=sc.next();
System.out.println("Enter the EmployeePhone Number:");
emp_phone=sc.nextInt();
}
void display() )
{
System.out.println("Employee Name:"+emp_name);
System.out.println("Employee ID:"+emp_id);
System.out.println("Employee Address:"+emp_address);
System.out.println("Employee Mail-ID:"+emp_mailid);
System.out.println("Employee Phone number :"+emp_phone);
class professor extends employee
{
employee e=new employee();
void cal_pro()
{
System.out.println("Enter the Basic Pay "); BP=sc.nextInt();
DA=BP*0.97; HRA=BP*0.10; PF=BP*0.12; SC=SC*.001;
NET=BP+DA+HRA-(PF+SC);
System.out.println("********************** PAY
SLIP**************************");
System.out.println("NET Pay:"+NET);
}
}
Output:
Result:
Thus the java program to create an employee pay slip by using the inheritance
concept
was executed successfully.
Outcome:
Thus the student can know to implement concept of inheritance using Java.
Applications:
VivaVoce:
1. Can you instantiate an object for a class that has a subclass overriding all the constructors of its
base class?
2. Is super class instantiated when subclass is instantiated?
3. Can a base-type access properties in its sub-types?
4. What is method overloading and method overriding?
5. Define inheritance
6. List the types of inheritance
7. Why multiple Inheritance is not supported by Java?
8.How to use Inheritance in Java?
9.What is the difference between Inheritance and Encapsulation?
10.Can we override static method in Java?
Ex:No 4 AREA CALCULATION USING ABSTRACT CLASS
AIM
PROGRAM
import java.io.*; import java.util.*; abstract class shape
{
int area;
abstract void printarea();
}
class rectangle extends shape
{
void printarea()
{
int l,b;
Scanner sc=new Scanner(System.in); System.out.println("Enter the length of the
rectangle"); l=sc.nextInt();
System.out.println("Enter the breadth of the rectangle");
b=sc.nextInt();
OUTPUT:
Result:
Thus the java program to performarea calculation using abstract class was executed
successfully.
Applications:
(1) Volum eo fth e Cube
(2) LengthoftheCube
Viva-Voce
1.What is abstract class in java?
2.How can we define an abstract class?
3. How to declare an abstract method?
4. Can we define abstract class without abstract method?
5.Can we create object object for abstract class?
6. Is is possible to declare abstract method as static?
7.Can we declare abstract method as final?
8. Is it possible to declare abstract method as private?
9. Is it possible to declare abstract method as public ?
10. Is it possible to declare abstract method with default?
Ex:No 5 AREA CALCULATION USING ABSTRACT CLASS AND INTERFACE
AIM
OUTPUT:
Result:
Thus the java program to perform area calculation using abstract class was executed
successfully.
Viva Voce
AIM
Write a program in java to implement user defined exception handling .
ALGORITHM
Step1: Create user defined exception.
Step2: Assign numbers for each exception.
Step3: Throw the exception and display the exception number.
PROGRAM
import java.io.*;
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}
OUTPUT
Result:
Thus the java program to implement user defined exception handling was executed
successfully
Outcome:
Thus the student can know toapplytheconceptofExceptionhandling for anuser definedexceptionusing Java.
Applications:
Program:
import java.util.Random;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );
}
}
Result:
Thus a Java program that implements a multi-thread application that has three threads. First thread
generates a random integer for every 1 second; second thread computes the square of the number
and prints; third thread will print the value of cube of the numberimplemented and executed
successfully.
Outcome:
Thus the student can know toapplythe concept of arraylist for string manipulations
using Java.
Viva-Voce
1. What is interface in java?
4.Which keyword java compiler add before interface fields and methods?
exist message Step4: Print the file type, Read or write property and
String line =
null; try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
Result:
Thus the java program to read a file and display its properties was executed successfully
Outcome:
Thus the student can know toapplythe file operations using Java..
Applications:
(1) IRCTC chartdisplay (RACreservatio n)
(2) A2Bmenudisplay
Viva-Voce
1. What are the basic methods in File class?
2. How do you handle directories in Java?
3. How do you write to a file using FileWriter class?
4. How do you read from a file using FileReader class?
5. What is the use of BufferedWriter and BufferedReader classes in Java?
6. What is the use of PrintWriter class?
7. What is a IO stream?
8. What is the necessity of two types of streams – byte streams and character streams?
9. What are the super most classes of all streams?
10. Which you feel better to use – byte streams or character streams?
Ex:No: 9 MAXIMUM VALUE USING GENERIC FUNCTION
AIM
To write java program to find the maximum value of an array using generic function.
ALGORITHM
Step1: Assign a list of integer and floating point values .
Step2: Create a class and assign generic template variables .
Step3: Assign the first value as max value ,compare it with other values ,if it is maximum reassign
the max value.
Step4:Display the maximum value
PROGRAM
import java.io.*;
import java.lang.*;
class genericdemo
{
public static <E extends Comparable<E>> E getLargestElement(E[] list)
{
E max = list[0]; // set first value in array as current max
for(int i = 1; i < list.length; i++)
{
if(list[i].compareTo(max) > 0 )
{
max = list[i];
}
}// end for
System .out.println(m ax);
return(max);
}
} // end main
}
OUTPUT
Result:
Thus the java program to find the maximum value of an array using generic function was
executed successfully
Outcome:
Thus the student can know toapplythe concept of generic function to generate maximum
value and minimum value. .
Applications:
AIM:
To write a java program for creating Edit menu for Notepad using event driven
programming
ALGORITHM
1. Create a Frame
2. Create objects for Menu bar ,Menu and menu item
3. Add the menu bar in frame, menu in menu bar and menu items in menu
4. Write the action listener for menu items and perform copy ,paste, select all operation
.
PROGRAM
mport javax.swing.*;
import java.awt.event.*;
public class MenuExample implements
ActionListener{ JFrame f;
JMenuBar mb;
JMenu
file,edit,help;
JMenuItem
cut,copy,paste,selectAll;
JTextArea ta; JButton b1;
MenuExample(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new
JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
b1=new JButton("Welcome to this
program"); ta.setBounds(5,5,360,320);
b1.setBounds(361,321,460,420);
f.add(mb);f.add(ta); f.add(b1);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(800,800);
f.setVisible(true);
}
public void actionPerformed(ActionEvent
e) {if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAl
l) ta.selectAll();
}
public static void main(String[]
args) {new MenuExample();
}
}
Output:
Result:
Thus the java program for creating Edit menu for Notepad using event driven
programming was executed successfully.
Outcome:
Thus the student can know to apply the concept of event handling and menu.
Applications:
(1) Age calculator
(2) EB calculator
Viva-Voce
1.What is the Purpose of Event
class?
5. When should we use an event adapter class?
6. What is the relationship between clipping and repainting?
7. What is the relationship between an event-listener interface and an event-
adapter class? 8.Difference between the paint() and repaint() methods
9.What is the purpose of the enableEvents()