0% found this document useful (0 votes)
35 views47 pages

Oops Lab Manual

Uploaded by

jessi
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)
35 views47 pages

Oops Lab Manual

Uploaded by

jessi
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/ 47

DEPARTMENT OF COMPUTER SCINECE AND ENGINEERING

CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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 :

Revision Number: Revision Date :


VISION
 To be a centre of excellence in engineering and technology
 To produce technocrats who are technically competent, ethically strong for
advancement of the society.
MISSION
 To provide quality education in emerging technologies in accordance with industrial
trends.
 To build good research capabilities and support new innovations.

DEPARTMENT OF COMPUTER SCINENCE AND ENGINEERING

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

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineer ing


fundamentals and an engineering specialization to the solution of complex engineering problems.

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.

3. Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate consideratio n
for the public health and safety, and the cultural, societal, and environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

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.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with 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 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

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


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

CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


LT P C
0 0 3 1.5
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 grossand 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
TEXT BOOK: (T)

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

Write a java program to Solve problems by using sequential search, binary


search, and quadratic sorting algorithms

SEQUENTIAL SEARCH

Algorithm:

Step 1: Traverse the array


Step 2: Match the key element with array element
Step 3: If key element is found, return the index position of the array element
Step 4: If key element is not found, return -1

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

public static void initializeselectionSort(int n[]) {


int i, j, first, temp;
for (i = n.length - 1; i > 0; i--) {
first = 0; //initialize to subscript of first element
for (j = 1; j <= i; j++) //locate smallest element between 1 and i.
{
if (n[j] < n[first])
first = j;
}
temp = n[first]; //swap the smallest found in position i.
n[first] = n[i];
n[i] = temp;
}
}
}

OUTPUT
Insertion sort

Algorithm

1. Start inserting the values in array.


2. Assign the first value to first index.
3. For next value compare it with previous values.
4. If it is small from previous swap it from previous.
5. Else assign that value to next index.
6. Do that for all remaining values.
Program
import java.io.*;
public class InsertionSortEx {
public static void main(String a[]) {

//Numbers which are to be sorted

int n[] = {

124,

23,

43,

12,

177,

25,

2,

1,

67

};

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

initializeInsertionSort(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 asecnding order

public static void initializeInsertionSort(int n[]) {

for (int i = 1; i < n.length; i++) {

int j = i;

int B = n[i];

while ((j > 0) && (n[j - 1] > B)) {

n[j] = n[j - 1];

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 ?

5.Name few classes that are part of java.io package ?


6.Name few classes that are part of java.lang package ?
7.What are the advantages of a java package?
8.Define Packages in Java.
9.Why are the packages used?
10.Explain what is a predefined package in Java.
Ex: No 2 STACK AND QUEUE DATA STRUCTURES USING CLASSES AND OBJECTS

Aim

Write a java program to implement stack and queue data structures using classes and
objects.
QUEUE USING CLASSES AND OBJECT

Algorithm

o Step 1: IF REAR = MAX - 1


Write OVERFLOW
Go to step
[END OF IF]
o Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
o Step 3: Set QUEUE[REAR] = NUM
o Step 4: EXIT

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;
}

// dequeue function for removing the front element


public void dequeue()
{
// check for queue underflow
if (isEmpty())
{
System.out.println("No items in the queue,cannot delete");
System.exit(1);
}

System.out.println("Deleting " + arr[front]);

front = (front + 1) % cap;


n1--;
}

// enqueue function for adding an item to the rear


public void enqueue(int val)
{
// check for queue overflow
if (isFull())
{
System.out.println("OverFlow!!Cannot add more values");
System.exit(1);
}

System.out.println("Adding " + val);

rear = (rear + 1) % cap;


arr[rear] = val;
n1++;
}

// peek function to return front element of the queue


public int peek()
{
if (isEmpty())
{
System.out.println("Queue empty!!Cannot delete");
System.exit(1);
}
return arr[front];
}

// returns the size of the queue


public int size()
{
return n1;
}
// to check if the queue is empty or not
public Boolean isEmpty()
{
return (size() == 0);
}
public Boolean isFull()
{
return (size() == cap);
}

// Queue implementation in java


public static void main (String[] args)
{
// create a queue of capacity 5
Queue q = new Queue(5);

q.enqueue(10);
q.enqueue(20);
q.enqueue(30);

System.out.println("Front element is: " + q.peek());

q.dequeue();
System.out.println("Front element is: " + q.peek());

System.out.println("Queue size is " + q.size());

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()
{

System.out.println("Enter the number of elements limit:"); no=sc.nextInt();


do
{

System.out.println("\n 1.Push\n 2.Pop"); choice=sc.nextInt();


if(choice==1)
{
do
{
if(top<no)
{
System.out.println("Enter the element of the stack:"); ele=sc.nextInt();

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?

2. What is the thread?

3. Differentiate between process and thread?

4. Define Constructor.

5.What is copy 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

Step5: Calculate the net salary

Net salary= (Basic pay + HRA + DA)-(PF+ staff club amount)


Step6: Display the PAY SLIP

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:

(1) EBBillG en eratio n (2) Incom e TaxCalculation

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

To write a program in java to implement abstract class.


ALGORITHM
Step 1: Create an abstract class named shape.
Step 2: Create rectangle, triangle, circle class, Make the classes extend the shape class.
Step 3: Calculate the area of rectangle, triangle and circle class.
Step 4: Print the area of the given shape.

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

System.out.println("Area of the rectangle is:"+l*b);


}
}
class triangle extends shape
{
void printarea()
{
int b,h;
Scanner sc=new Scanner(System.in); System.out.println("Enter the breadth of the
triangle");
b=sc.nextInt();
System.out.println("Enter the height of the triangle"); h=sc.nextInt();

System.out.println("Araea of the triangle is:"+0.5*b*h);


}
}
class circle extends shape
{
void printarea()
{
int r;
Scanner sc=new Scanner(System.in); System.out.println("Enter the radious of the circle");
r=sc.nextInt();

System.out.println("Area of the circle is:"+3.14*r*r);


}
}
class abstractmain
{
public static void main(String args[])
{
shape r=new rectangle(); r.printarea();
shape t=new triangle(); t.printarea();
shape c=new circle(); c.printarea();
}
}

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

To write a program in java to implement abstract class and interface .


ALGORITHM
Step 1: Create an abstract class named shape.
Step2: Create a interface called demo shape
Step 3: Create rectangle, triangle, circle class, Make the classes extend the shape class and
implements demoshape interface .
Step 4: Calculate the area of rectangle, triangle and circle class.
Step 5: Print the area of the given shape.
PROGRAM
import java.io.*;
import java.util.*;
interface demoshape
{
final int area=0;
}
abstract class shape
{
abstract void printarea();
}
class rectangle extends shape implements demoshape
{
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();

System.out.println("Area of the rectangle is:"+l*b);


}
}
class triangle extends shape implements demoshape
{
void printarea()
{
int b,h;
Scanner sc=new Scanner(System.in);

System.out.println("Enter the breadth of the triangle");


b=sc.nextInt();
System.out.println("Enter the height of the triangle");
h=sc.nextInt();

System.out.println("Araea of the triangle is:"+0.5*b*h);


}
}
class circle extends shape implements demoshape
{
void printarea()
{
int r;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radious of the circle");
r=sc.nextInt();

System.out.println("Area of the circle is:"+3.14*r*r);


}
}
class abstractmain
{
public static void main(String args[])
{
shape r=new rectangle();
r.printarea();
shape t=new triangle();
t.printarea();
shape c=new circle();
c.printarea();
}
}

OUTPUT:
Result:
Thus the java program to perform area calculation using abstract class was executed
successfully.

Viva Voce

1.Define abstract class


2.Explain interface
3.What is mean by abstract method
4.What is the use of final keyword
5.Write the syntax for using interface in java
Ex: No 6 EXCEPTION HANDLING

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:

(1) Throwingex ceptio nfo r Checkingthe@ symbolin Em ailId

(2) Throwingex ceptio nfo r passwo rd mismatch.


Viva-Voce

1. What is Exception in Java?


2. What are the Exception Handling Keywords in Java?
3. Explain Java Exception Hierarchy?
4. What are important methods of Java Exception Class?
5. Explain Java 7 ARM Feature and multi-catch block?
6. What is difference between Checked and Unchecked Exception in Java?
7. What is difference between throw and throws keyword in Java?
8. How to write custom exception in Java?
9. What is OutOfMemoryError in Java?
10. What is difference between final, finally and finalize in Java?
EX:NO 7 MULTI-THREADED APPLICATION
AIM
Write 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 number.
Algorithm

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

class Number extends Thread


{
public void run()
{
Random random = new Random();
for(int i =0; i<5; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
Square s = new Square(randomInteger);
s.start();
Cube c = new Cube(randomInteger);
c.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
public class Thr {
public static void main(String args[])
{
Number n = new Number();
n.start();
}
}
Output:

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?

2. Can we create an object of an interface?

3.Can we declare the interface as final?

4.Which keyword java compiler add before interface fields and methods?

5.Does interface extend Object class by default?


Ex: NO :8 FILE PROGRAM
AIM
To write a program in java read a file and display its properties.
ALGORITHM
Step1: Read the input file from the user.
Step2: Read character by character Print the values until the end of
the file. Step3: Check whether the file exist, if available print file

exist message Step4: Print the file type, Read or write property and

length of the file PROGRAM:


import
java.util.Scanner;
import java.io.*;
import
java.lang.*; class
fileprogram
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);

/* enter filename with extension to open and read its content */

System.out.print("Enter File Name to Open (with extension like


file.txt) : "); fname = scan.nextLine();
File f=new
File(fname);
if(f.exists())
{
System.out.println("File Exisit");
System.out.println("File Length = " +
f.length()); if(f.canRead())
System.out.println("Can read the
file"); else
System.out.println("Can't Read the
file"); if(f.canWrite())
System.out.println("Can Write the
file"); else
} System.out.println("Can't write the file");
els
e
{
System.out.println("File not found");
}
/* this will reference only one line at a time */

System.out.println("***************THE CONTENT OF THE


FILE*********************");

String line =
null; try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);

/* always wrap the FileReader in BufferedReader */


BufferedReader bufferedReader = new
BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null)


{
System.out.println(line);
}

/* always close the file after


use */ bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
OUTPUT

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

public static void main(String args[])


{
// create arrays of Integer, Double and Character
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
System.out.println("Max value of
integerArray is:");
getLargestElement(integerArray); // pass an Integer array
System.out.println("\nMax value of floatArray is:");
getLargestElement(doubleArray); // pass a Double array

} // 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:

(1) Finding even values


(2). Finding the sum of value
Viva-Voce
1. What is a Generic Type Parameter?
2. What Are Some Advantages of Using Generic Types?
3. What is Type Erasure?
4. If a Generic Type is Omitted When Instantiating an
5. How Does a Generic Method Differ From a Generic Type?
6. What is Type Inference?
7. What is a Bounded Type Parameter?
8. Is it Possible to Declared a Multiple Bounded Type Parameter?
9. What is a Wildcard type?
10. What is an Upper Bounded Wildcard?
Ex: No 10 DESIGN A EDIT MENU FOR NOTEPAD

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

object 2.What is an action event?


3.Different kinds of event
listeners 4.What is event adapter

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()

method? 10.Difference between a Scrollbar and a


ScrollPane 11.Scrollbar and a ScrollPane

You might also like