[go: up one dir, main page]

0% found this document useful (0 votes)
4 views36 pages

OOPS LAB RECORD

Uploaded by

kayal.professor
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)
4 views36 pages

OOPS LAB RECORD

Uploaded by

kayal.professor
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/ 36

BONAFIDE

CERTIFICATE

This is to certify that, this a bonafide record work done by

Mr. /Ms……………………………………………………Year………Semester……………

Register No. ………………………………For .......................................... Program

In the School of…………………………………………………………………………………

at JEPPIAAR UNIVERSITY, CHENNAI during the academic year 2023-2024.

……………… …………………
Signature Signature

Faculty In-Charge Dean

Submitted for Jeppiaar University Practical Examination Held On ……………….

………………………. ………………………….
Signature Signature

Internal Examiner (With Date) External Examiner (With Date)

ECS13008 - Object oriented programming


INDEX

STAFF
SNO DATE EXPERIMENT MARK SIGN

1 Demonstration of Linear search, Insertion Sort

2 Implementation of Class and object stack Operation, Queue


push and pop

3 Demonstration of Inheritance

4 Implementation of Abstract class and Abstract method

5 Implementation of Interface

6 Implementation of Exception Handling

7 Implementation of Multithreading

8 Implementation of File Input/output


Date:
Date:
Exercise no :2

Exercise name: Program to demonstrate the Class and Object,Stack


Operation,Queue Push and Pop.

Aim: The aim of this program is to demonstrate the use of classes and
objects,perform stack operations,and exhibit queue push and pop operations
using custom classes in java.

Algorithm:
1. Class and Object(MyClass):
-Create a class’MyClass’ to represent an object with an integer value.
-Create an object of the ‘MyClass’ class with an initial value.
-Print the value stored in the object.
2. Stack Operations(Stack Class);
-Create a custom class that supports generic data types and it implement the
‘Push’ method to add elements to the stack. And ‘Pop’ method to remove and
return elements from the stack.
-Check for stack eptiness with the ‘isEmpty’ method.
3. Queue Push and Pop(Queue Class):
-Create a custom ‘Queue’ class that supports generic data types and it
implement the ‘Push’ method to add elements to the queue and ‘Pop’method to
remove and return elements from the queue.
-Check for queue emptiness with the ‘isEmpty’ method.
Program:
#Java program that implements a class and object,stack operations,push and pop
using custom classes

import java.util.ArrayList;
Class MyClass {
int value;
public MyClass(int value) {
this.value = value;
}
Public void printvalue() {
System.out.println(“Value: “ + value);
}
}
Class Stack<T> {
Private Arraylist<T> elements = new Arraylist<>();
Public void push(T element) {
elements.add(element);
}
Public T pop() {
If (!isEmpty()) {
Return
elements..remove(elements.size() – 1);
}
return null;
}
Public boolean isEmpty() {
return elements.isEmpty();
}
}
Class Queue<T> {
Private ArrayList<T> elements =
New ArrayList<>();
Public void push(T element) {
elements.add(element):
}
Public T pop() {
If (!isEmpty()) {
return element.remove(0);
}
return null;
}
Public Boolean isEmpty() {
return elements.isEmpty();
}
}
Public class Main {
Public static void main(String[]args) {
// Class and Object example
Myclass myobject = new
MyClass(42);
myobject.ptintvalue();

// Stack example
Stack<Integer> stack = new
Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);

System.out.println(“Stack Operations:”);
While(!stack.isEmpty()) {
Int element = stack.pop();
System.out.println(“Popped from Stack: “ + element);
}

// Queue example
Queue<Integer> queue = new Queue<>();
queue.push(4);
queue.push(5);
queue.push(6);

System.out.println(“Queue Push and Pop:”);


While (!queue.isEmpty()) {
Int element = queue.pop();
System.out.println(“Removed from Queue: “ + element);
}
}
}
Output:
Value: 42
Stack Operations:
Popped from Stack: 3
Popped from Stack: 2
Popped from Stack: 1
Queue Push and Pop:
Removed from Queue: 4
Removed from Queue: 5
Removed from Queue: 6
Date:
Date:
Exercise no : 4

Exercisename: Programtodemonstratetheusageofabstractclass andabstractmethod.

Aim :

Algorithm:

Create an abstract class named Shape.


DeclareanabstractmethodnamedprintArea.
CreateaclassnamedRectanglethatextendsShape.
Implementthe PrintAreamethodforRectangle.
Createa class named Triangle that extends Shape.
ImplementthePrintArea methodforTriangle.
CreateaclassnamedCirclethatextendsShape.
Implementthe PrintAreamethodforCircle
Program:

abstract class Shape { protected int length;

protectedintwidth;

publicShape(intlength,intwidth){ this.length=length;
this.width=width;
}

publicabstractvoidprintArea();
}

classRectangleextendsShape{
publicRectangle(intlength,intwidth){ super(length,width);
}

@Override
publicvoidprintArea(){
intarea=length*width; System.out.println("AreaofRectangle:"+area);
}
}

class Triangle extends Shape { publicTriangle(intlength,intwidth){


super(length, width);
}

@Override
publicvoidprintArea(){
doublearea=0.5*length*width; System.out.println("Area ofTriangle:"+ area);
}
}

classCircleextendsShape{ publicCircle(intradius){
super(radius,0);
}

@Override
publicvoidprintArea(){
doublearea=Math.PI*length*length; System.out.println("AreaofCircle:"+area);
}

publicclassMain{
public static void main(String[] args) { Rectanglerectangle =new Rectangle(4, 5); Triangle
triangle=newTriangle(3,6); Circlecircle= new Circle(7);

rectangle.printArea(); triangle.printArea(); circle.printArea();


}
}
ThisprogramdefinestheShapeabstractclasswithtwointegers
(lengthandwidth)andan abstractmethodprintArea(). TheRectangle, Triangle,andCi.

Output:
Areaof Rectangle: 20 Area of Triangle: 9.0
Area of Circle: 153.93804002589985
Date:
Exercise no. 5

Exercise name: PROGRAM TO DEMONSTRATE THE USAGE OF


INTERFACE IN JAVA
AIM:
Write a Java Program to create an interface named Shape that contains two
integers and an empty method named printArea(). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes
extends the class Shape. Each one of the classes contains only the method
printArea( ) that prints the area of the given shape.

ALGORITHM:
1. Define an interface named "Shape" with an abstract method "printArea."

2. Create a class called "Rectangle" that implements the "Shape" interface.


It has private fields for length and width, a constructor to initialize these
values, and an implementation of the "printArea" method to calculate and
print the area of the rectangle.
3. Create a class called "Triangle" that also implements the "Shape"
interface. It has private fields for the base and height, a constructor to
initialize these values, and an implementation of the "printArea" method to
calculate and print the area of the triangle.
4. Create a class called "Circle" that implements the "Shape" interface. It
has a private field for the radius, a constructor to initialize this value, and an
implementation of the "printArea" method to calculate and print the area of
the circle.
5. In the "Main" class:

a. Inside the "main" method, create an instance of the "Rectangle" class


with a length of 5 and a width of 10. This is done by using the "Shape"
interface as the reference type.
b. Call the "printArea" method on the "rectangle" object, which will
calculate and print the area of the rectangle.

6. Repeat steps 5a and 5b for the "Triangle" and "Circle" classes:


a. Create instances of the "Triangle" and "Circle" classes with specific
values for their dimensions.
b. Call the "printArea" method on these objects to calculate and print the
areas of the triangle and circle, respectively.

7. When you run the program, it will output the areas of the rectangle,
triangle, and circle to the console.

PROGRAM:
#Java program that defines an interface named Shape with two integers
(representing dimensions) and an empty method named printArea. Three
classes, Rectangle, Triangle, and Circle, extend the Shape interface and
provide implementations for the printArea method.

interface Shape {
void printArea();
}
class Rectangle implements Shape {
private int length;
private int width;

public Rectangle(int length, int width) {


this.length = length;
this.width = width;
}
@Override
public void printArea() {
int area = length * width;
System.out.println("Area of Rectangle: " + area);
}
}
class Triangle implements Shape {
private int base;
private int height;

public Triangle(int base, int height) {


this.base = base;
this.height = height;
}
@Override
public void printArea() {
double area = 0.5 * base * height;
System.out.println("Area of Triangle: " + area);
}
}
class Circle implements Shape {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
@Override
public void printArea() {
double area = Math.PI * radius * radius;
System.out.println("Area of Circle: " + area);
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 4);
Triangle triangle = new Triangle(6, 8);
Circle circle = new Circle(3);
rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}

This program defines the Shape interface, implements it in the Rectangle,


Triangle, and Circle classes, and demonstrates how to calculate and print the
areas of these shapes.

OUTPUT:
Area of Rectangle: 20
Area of Triangle: 24.0
Area of Circle: 28.274333882308138
Date:
Exercise no: 6
Exercise name: Implement exception handling and creation of user defined
exceptions

AIM:
To write a program to implement exception handling and creation of user defined
exceptions

ALGORITHM:
1. Define a class named "ExceptionalHandling" that extends the built-in
Exception class. This custom exception is used to handle odd numbers.
2. Inside the main method:
a. Declare an integer variable "num" to store the user's input.
b. Create a Scanner object "in" to read input from the user.
3. Start an infinite while loop using "while (true)" to repeatedly prompt the user
for input until they provide an even number.
4. Inside the try block:
a. Create an instance of the "ExceptionalHandling" custom exception with the
message "Odd number".
b. Display a message asking the user to enter an even number.
c. Read the user's input as an integer and store it in the "num" variable.
d. Check if the entered number is odd by using the condition "if (num % 2 ==
1)".
e. If the number is odd, throw the custom exception "ex" to trigger the catch
block.
5. In the catch block:
a. Catch the custom exception "e" and display a message indicating that an
exception has been caught, along with the exception message obtained using
"e.getMessage()".
6. If an even number is entered (no exception is thrown), exit the while loop
using the "break" statement
7. After exiting the loop, display a message to indicate that an even number has
been achieved.
PROGRAM:
import java.util.Scanner;
public class ExceptionalHandling extends Exception {
public ExceptionalHandling(String s) {
super(s);
}
public static void main(String[] args) {
int num;
Scanner in = new Scanner(System.in);
while (true) {
try {
ExceptionalHandling ex = new ExceptionalHandling("Odd number");
System.out.print("Enter an even number: ");
num = in.nextInt();
if (num % 2 == 1)
throw ex;
break;
} catch (ExceptionalHandling e) {
System.out.println("Caught Exception ("+e.getMessage()+")");
}
}
System.out.println("Even number is achieved!");
}
}

INPUT:
3
5
4
OUTPUT:
Date:
Exercise no: 7

Exercise name: Program to demonstrate the usage of Multi-threading


in Java

Aim : Java program to implement 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.

Algorithm :

1) Create a RandomNumberGenerator class that implements the Runnable


interface.In its run method, generate random numbers and
2) create threads to calculate and print squares or cubes for even or odd
numbers.
3) Create EvenSquareThread and OddCubeThread classes, both
implementing Runnable, to calculate squares and cubes.
4) In the MultiThreadExample class, create a thread for
RandomNumberGenerator, and start it in the main method.
5) The program generates random numbers, creates threads for
calculations, and prints results based on even or odd numbers using
multiple threads.
Program :
# Java program that implements a multi-threaded application with
three threads to achieve the described functionality

import java.util.Random;
class RandomNumberGenerator implements Runnable {
@Override public
void run()
Random rand = new Random(); while (true) {
int randomNum = rand.nextInt(100); // Generate a random integer
between 0 and 99
System.out.println("Generated: " + randomNum);

if (randomNum % 2 == 0) {
EvenSquareThread squareThread = new
EvenSquareThread(randomNum);
Thread thread = new Thread(squareThread);
thread.start();
} else {
OddCubeThread cubeThread = new
OddCubeThread(randomNum);
Thread thread = new Thread(cubeThread);
thread.start();
}

try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class EvenSquareThread implements Runnable {


private int number;

public EvenSquareThread(int num) {


number = num;
}

@Override public
void run() {
int square = number * number;
System.out.println("Even Square: " + square);
}
}

class OddCubeThread implements Runnable {


private int number;

public OddCubeThread(int num) {


number = num;
}

@Override public
void run() {
int cube = number * number * number;
System.out.println("Odd Cube: " + cube);
}
}
public class MultiThreadExample {
public static void main(String[] args) {

Thread generatorThread = new Thread(new


RandomNumberGenerator());
generatorThread.start();
}
}

Output :

Generated: 47
Odd Cube: 103823
Generated: 88
Even Square: 7744
Generated: 15
Odd Cube: 3375
Generated: 3
Odd Cube: 27
Generated: 64
Even Square: 4096
Date:
Exercise no: 8
Exercise name: FILE I\O OPERATION
AIM: TO WRITE A PROGRAM ON FILE INPUTSTREAM AND FILE OUTPUT
STREAM

Stream A stream can be defined as a sequence of data. there are two kinds of
Streams
InPutStream: The InputStream is used to read data from a source.
OutPutStream: the OutputStream is used for writing data to a
destination.

FileInputStream: This stream is used for reading data from the files. Objects can be
created using the keyword new and there are several types of constructors
available.
Following constructor takes a file name as a string to create an input stream
object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read
the file. First we create a file object using File method as follows
File f = new File("C:/java/hello"); InputStream f = newFileInputStream(f);
FileOutputStream: FileOutputStream is used to create a file and writedata into it.
The stream would create a file, if it doesn't already exist, before opening it for
output.
Here are two constructors which can be used to create a
FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object
to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to
write the file. First, we create a file object using File method asfollows:
File f = new File("C:/java/hello"); OutputStream f = newFileOutputStream(f);
ALGORITHM:
1. OPEN THE FILE
2. PROCESS THE FILE (READ/WRITE)
3. CLOSE THE FILE
4. FILE INPUT (READING FROM THE FILE)
5. FILE OUTPUT(WRITING TO A FILE)PROGRAM

PROGRAM:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader; import
java.io.FileWriter; import
java.io.IOException;

public class FileIO {


public static void main(String[] args) {

String[] names = {"John", "Carl", "Jerry"};try {


BufferedWriter writer = new BufferedWriter(newFileWriter("output.txt"));
writer.write("Writing to a file.");
writer.write("\nHere is another line.");

for (String name : names) {


writer.write("\n" + name);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new
FileReader("output.txt"));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT:

You might also like