3 - Sem - Bcs306a - Oop With Java - Lab - Manual - 2023-24

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

SIR M VISVESVARAYA INSTITUTE OF TECHNOLOGY

(Affiliated to VTU, Recognized by AICTE and Accredited by NBA, NAAC


and an ISO 9001-2008 Certified Institution)
Bengaluru – 562157

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

OBJECT ORIENTED PROGRAMMING WITH JAVA

CHOICE BASEDCREDITSYSTEM

BCS306A - III Semester B.E


(Academic Year 2023-24)

Compiled and Prepared by: Under the Guidance of:


Ms. Savitha P Dr. Anitha T N
Assistant Professor Professor & Head
Dept. of CSE Dept. of CSE

Department Vision and Mission


VISION
To build a center for imparting quality technical education and carrying out research activity
to meet the current and future challenges in the domain of Computer Science and Engineering.

MISSION
• The Computer Science and Engineering department strives for excellence in teaching,
applying, promoting and imparting knowledge through comprehensive academic curricula.
• Train students to effectively apply the knowledge to solve real-world problems, thus enhance
their potential for life-long high-quality career and give them a competitive advantage in the
ever-changing and fast paced computing.
• Prepare students to demonstrate a sense of societal and ethical responsibilities in their
professional endeavors.
• Creating amongst students and faculty a collaborative environment open to the free exchange
of ideas, which leads to research activity and fuels innovation thinking.
PROGRAM OUTCOMES

PO's PO Description
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex
engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2 complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
PO3
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
PO4 research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO5 modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge
PO6 to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
PO8
responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member
PO9
or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
PO10
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a
PO11
member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
PO12 engage in independent and life-long learning in the broadest context of technological
change.

PROGRAM SPECIFIC OUTCOMES

PSO's PSO Description


An ability to design and analyze algorithms by applying theoretical concepts to build complex
PSO1 and computer- based systems in the domain of System Software, Computer Networks &
Security, Web technologies, Data Science and Analytics.
Be able to develop various software solutions by applying the techniques of Data Base
PSO2 Management, Complex Mathematical Models, Software Engineering practices and Machine
Learning with Artificial Intelligence.
OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

Object Oriented Programming with JAVA Semester 3


Course Code BCS306A CIE Marks 50
Teaching Hours/Week (L: T:P: S) 2:0:2 SEE Marks 50
Total Hours of Pedagogy 28 Hours of Theory + 20 Hours of Practical Total Marks 100
Credits 03 Exam Hours 03
Examination type (SEE) Theory
Programming Experiments (Suggested and are not limited to)
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be read from
command line arguments).
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main method
to illustrate Stack operations.
3. A class called Employee, which models an employee with an ID, name and salary, is designed as shown in
the following class diagram. The method raiseSalary (percent) increases the salary by the given percentage.
Develop the Employee class and suitable main method for demonstration.
4. A class called MyPoint, which models a 2D point with x and y coordinates, is designed as follows:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another point at the
given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test all the
methods defined in the class.
5. Develop a JAVA program to create a class named shape. Create three sub classes namely: circle, triangle
and square, each class has two member functions named draw() and erase (). Demonstrate
polymorphism concepts by developing suitable methods, defining member data and main program.
6. Develop a JAVA program to create an abstract class Shape with abstract methods calculateArea() and
calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and implement the
respective methods to calculate the area and perimeter of each shape.
7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width) and
resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that implements the
Resizable interface and implements the resize methods
8. Develop a JAVA program to create an outer class with a function display. Create another class inside the
outer class named inner with a function called display and call the two functions in the main class.
9. Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero using try,
catch, throw and finally.
10. Develop a JAVA program to create a package named mypack and import & implement it in a suitable class.
11. Write a program to illustrate creation of threads using runnable class. (start method start each of the newly
created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).
12. Develop a program to create a class MyThread in this class a constructor, call the base class constructor,
using super and start the thread. The run method of the class starts after this. It can be observed that both
main thread and created child thread are executed concurrently.

Department of Computer Science and Engineering, Sir MVIT Page | 1


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
read from command line arguments).

import java.util.Scanner;

class AddMatrix
{
public static void main(String args[])
{
int row, col,i,j;
Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows");


row = in.nextInt();

System.out.println("Enter the number columns");


col = in.nextInt();

int mat1[][] = new int[row][col];


int mat2[][] = new int[row][col];
int res[][] = new int[row][col];

System.out.println("Enter the elements of matrix1");

for ( i= 0 ; i < row ; i++ )


{

for ( j= 0 ; j < col ;j++ )


mat1[i][j] = in.nextInt();

System.out.println();
}
System.out.println("Enter the elements of matrix2");

for ( i= 0 ; i < row ; i++ )


{

for ( j= 0 ; j < col ;j++ )


mat2[i][j] = in.nextInt();

System.out.println();
}

for ( i= 0 ; i < row ; i++ )


for ( j= 0 ; j < col ;j++ )
res[i][j] = mat1[i][j] + mat2[i][j] ;

System.out.println("Sum of matrices:-");

Department of Computer Science and Engineering, Sir MVIT Page | 2


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

for ( i= 0 ; i < row ; i++ )


{
for ( j= 0 ; j < col ;j++ )
System.out.print(res[i][j]+"\t");

System.out.println();
}

}
}

Department of Computer Science and Engineering, Sir MVIT Page | 3


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA
main method to illustrate Stack operations.

// Stack implementation in Java

class Stack {

// store elements of stack


private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;

// Creating a stack
Stack(int size) {
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
}

// push elements to the top of stack


public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");

// terminates the program


System.exit(1);
}

// insert element on top of stack


System.out.println("Inserting " + x);
arr[++top] = x;
}

// pop elements from top of stack


public int pop() {

// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
// terminates the program
System.exit(1);
}

// pop element from top of stack

Department of Computer Science and Engineering, Sir MVIT Page | 4


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

return arr[top--];
}

// return size of the stack


public int getSize() {
return top + 1;
}

// check if the stack is empty


public Boolean isEmpty() {
return top == -1;
}

// check if the stack is full


public Boolean isFull() {
return top == capacity - 1;
}

// display elements of stack


public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}

public static void main(String[] args) {


Stack stack = new Stack(5);

stack.push(1);
stack.push(2);
stack.push(3);

System.out.print("Stack: ");
stack.printStack();

// remove element from stack


stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();

}
}

Department of Computer Science and Engineering, Sir MVIT Page | 5


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

3.A class called Employee, which models an employee with an ID, name and salary, is designed as
shown in the following class diagram. The method raiseSalary (percent) increases the salary by the
given percentage. Develop the Employee class and suitable main method for demonstration.

public class Employee {


private int id;
private String name;
private double salary;

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

public void raiseSalary(double percent) {


double increase = salary * (percent / 100);
salary += increase;
}

// Getters and setters for the fields (ID, name, salary)


public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

public String toString() {


return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
}

Department of Computer Science and Engineering, Sir MVIT Page | 6


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

public static void main(String[] args) {


// Demonstration in main method
Employee emp = new Employee(1, "John Doe", 50000);
System.out.println("Original Details:");
System.out.println(emp);

// Raise salary by 10%


emp.raiseSalary(10);
System.out.println("\nAfter 10% Raise:");
System.out.println(emp);
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 7


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

4. A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:

● Two instance variables x (int) and y (int).


● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another
point at the given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to
the given MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the
origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint)
to test all the methods defined in the class.

public class MyPoint {


private int x;
private int y;

// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}

// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

// Set both x and y


public void setXY(int x, int y) {
this.x = x;
this.y = y;
}

// Return x and y in a 2-element int array


public int[] getXY() {
int[] xy = {x, y};
return xy;
}

// Returns a string description of the instance in the format "(x, y)"

Department of Computer Science and Engineering, Sir MVIT Page | 8


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

public String toString() {


return "(" + x + ", " + y + ")";
}

// Distance from this point to another point at given (x, y) coordinates


public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}

// Distance from this point to another MyPoint instance


public double distance(MyPoint another) {
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}

// Distance from this point to the origin (0, 0)


public double distance() {
return Math.sqrt(x * x + y * y);
}
}

///////////////////////////

public class TestMyPoint {


public static void main(String[] args) {
// Create a MyPoint object using default constructor
MyPoint point1 = new MyPoint();
System.out.println("Point 1: " + point1); // Output: (0, 0)

// Create a MyPoint object using overloaded constructor


MyPoint point2 = new MyPoint(3, 4);
System.out.println("Point 2: " + point2); // Output: (3, 4)

// Set new x and y coordinates using setXY method


point1.setXY(-2, 1);
System.out.println("Point 1 after setXY: " + point1); // Output: (-2, 1)

// Get x and y coordinates using getXY method


int[] coordinates = point2.getXY();
System.out.println("Point 2 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")"); // Output: (3, 4)

// Calculate distance between two points


System.out.println("Distance between Point 1 and Point 2: " + point1.distance(point2)); // Output: 5.0

// Calculate distance from Point 1 to a specified point (5, 2)

Department of Computer Science and Engineering, Sir MVIT Page | 9


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

System.out.println("Distance from Point 1 to (5, 2): " + point1.distance(5, 2)); // Output: 7.6157...

// Calculate distance from Point 2 to the origin (0, 0)


System.out.println("Distance from Point 2 to the origin: " + point2.distance()); // Output: 5.0
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 10


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

5. Develop a JAVA program to create a class named shape. Create three sub classes namely:
circle, triangle and square, each class has two member functions named draw() and
erase (). Demonstrate polymorphism concepts by developing suitable methods, defining
member data and main program.

public class TestShapes {


public static void main(String[] args) {
// Demonstrating polymorphism
Shape shape1 = new Circle();
Shape shape2 = new Triangle();
Shape shape3 = new Square();

// Calling draw and erase methods


shape1.draw();
shape1.erase();

shape2.draw();
shape2.erase();

shape3.draw();
shape3.erase();
}

}class Shape {
public void draw() {
System.out.println("Drawing a shape");
}

public void erase() {


System.out.println("Erasing a shape");
}
}

class Circle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a circle");
}

@Override
public void erase() {
System.out.println("Erasing a circle");
}
}

class Triangle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a triangle");
}

Department of Computer Science and Engineering, Sir MVIT Page | 11


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}

class Square extends Shape {


@Override
public void draw() {
System.out.println("Drawing a square");
}

@Override
public void erase() {
System.out.println("Erasing a square");
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 12


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

6. Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that extend
the Shape class and implement the respective methods to calculate the area and perimeter of
each shape.

abstract class Shape {


abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}

@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Triangle extends Shape {


private double side1, side2, side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 13


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

public class TestShapes {


public static void main(String[] args) {
// Creating instances of Circle and Triangle
Circle circle = new Circle(5);
Triangle triangle = new Triangle(3, 4, 5);

// Calculating area and perimeter for Circle


System.out.println("Circle:");
System.out.println("Area: " + circle.calculateArea());
System.out.println("Perimeter: " + circle.calculatePerimeter());

// Calculating area and perimeter for Triangle


System.out.println("\nTriangle:");
System.out.println("Area: " + triangle.calculateArea());
System.out.println("Perimeter: " + triangle.calculatePerimeter());
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 14


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int


width) and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle
that implements the Resizable interface and implements the resize methods

public class TestResizable {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(10, 20);

System.out.println("Original Width: " + rectangle.getWidth());


System.out.println("Original Height: " + rectangle.getHeight());

rectangle.resizeWidth(15);
rectangle.resizeHeight(25);

System.out.println("\nResized Width: " + rectangle.getWidth());


System.out.println("Resized Height: " + rectangle.getHeight());
}
}
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

class Rectangle implements Resizable {


private int width;
private int height;

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

public int getWidth() {


return width;
}

public int getHeight() {


return height;
}

@Override
public void resizeWidth(int width) {
this.width = width;
}
@Override
public void resizeHeight(int height) {
this.height = height;
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 15


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

8.Develop a JAVA program to create an outer class with a function display. Create another class
inside the outer class named inner with a function called display and call the two functions in the
main class.

class Outer {
void display() {
System.out.println("Outer class display()");
}

class Inner {
void display() {
System.out.println("Inner class display()");
}
}
}

public class OuterInnerDemo {


public static void main(String[] args) {
Outer outerObj = new Outer();
Outer.Inner innerObj = outerObj.new Inner();

// Calling display() of Outer class


outerObj.display();

// Calling display() of Inner class


innerObj.display();
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 16


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

9.Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.

// Custom exception class for DivisionByZero


class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
try {
int numerator = 10;
int denominator = 0;

if (denominator == 0) {
// If denominator is zero, throw the custom exception
throw new DivisionByZeroException("Division by zero is not allowed");
}

int result = numerator / denominator;


System.out.println("Result: " + result);

} catch (DivisionByZeroException e) {
// Catch the custom exception and handle it
System.out.println("Custom Exception Caught: " + e.getMessage());
} finally {
// Finally block executes whether an exception occurs or not
System.out.println("Finally block executed");
}
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 17


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

10.Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.

package mypack;

public class MyClass {


public void displayMessage() {
System.out.println("This is a message from mypack.MyClass");
}
}

/////////////////////////////

import mypack.MyClass;

public class TestPackage {


public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.displayMessage();
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 18


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

11.Write a program to illustrate creation of threads using runnable class. (start method start each of the
newly created thread. Inside the run method there is sleep() for suspend the thread for 500 milliseconds).

class MyRunnable implements Runnable {


private String threadName;

public MyRunnable(String threadName) {


this.threadName = threadName;
}

public void run() {


try {
System.out.println("Thread " + threadName + " is starting...");
Thread.sleep(500); // Suspend the thread for 500 milliseconds
System.out.println("Thread " + threadName + " is running...");
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " is exiting.");
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
System.out.println("Main thread is starting...");

// Create multiple threads using the Runnable interface


Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
Thread thread3 = new Thread(new MyRunnable("Thread 3"));

// Start each of the newly created threads


thread1.start();
thread2.start();
thread3.start();

System.out.println("Main thread is exiting...");


}
}

Department of Computer Science and Engineering, Sir MVIT Page | 19


OBJECT ORIENTED PROGRAMMING WITH JAVA BCS306A

12.Develop a program to create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts after this. It can
be observed that both main thread and created child thread are executed concurrently.

class MyThread extends Thread {


public MyThread(String name) {
super(name); // Calling base class constructor using super
start(); // Starting the thread
}

public void run() {


System.out.println("Child Thread is executing");
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread: " + i);
try {
Thread.sleep(500); // Suspend thread for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Child Thread interrupted");
}
}
System.out.println("Child Thread is exiting");
}
}

public class ThreadExample {


public static void main(String[] args) {
System.out.println("Main Thread is starting...");

MyThread childThread = new MyThread("Child Thread");

for (int i = 1; i <= 5; i++) {


System.out.println("Main Thread: " + i);
try {
Thread.sleep(1000); // Suspend main thread for 1 second
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted");
}
}

System.out.println("Main Thread is exiting...");


}
}

Department of Computer Science and Engineering, Sir MVIT Page | 20

You might also like