SHRI MADHWA VADIRAJA
INSTITUTE OF
TECHNOLOGY AND MANAGEMENT
Vishwothama Nagar, Bantakal – 574 115, Udupi Dist.
(A unit of Shri Sode Vadiraja Mutt Education Trust)
LABORATORY MANUAL
For
Object Oriented Programming with JAVA
(Effective from the academic year 2023-24)
Semester: III/IV SEMESTER B.E.
Subject code: BCS306A
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
1
III SEM
Object Oriented Programming with JAVA
Course Code BCS306A CIE Marks 50
TeachingHours/ 2:0:2 SEE Marks 50
Weeks(L:T:P:S)
Total Hours of Pedagogy 28 Hours of Theory + 20 Total Marks 100
Hours of Practical
Credits 03 Hours 03
Examination type (SEE) Theory
Course objectives:
● To learn primitive constructs JAVA programming language.
● To understand Object Oriented Programming Features of JAVA.
● To gain knowledge on: packages, multithreaded programming and exceptions.
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 raise Salary (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 resize Width(int width) and
resize Height(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 theouter 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 Division By Zero
using try, catch, throw and finally.
10) Develop a JAVA program to create a package named my pack and import & implement it in a
2
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
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE)
is 50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of
50) and for the SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A
student shall be deemed to have satisfied the academic requirements and earned the credits allotted
to each subject/ course if the student secures a minimum of 40% (40 marks out of 100) in the sum
total of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken
together
CIE for the theory component of the IPCC (maximum marks 50)
● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25
marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests
(Two Tests, each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other
assessment methods mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the
syllabus and the second test after covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for
the theory component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC
Web links and Video Lectures (e-Resources):
● Java Tutorial: [Link]
● Introduction To Programming In Java (by Evan Jones, Adam Marcus and Eugene Wu):
[Link]
● Java Tutorial: [Link]
● Java Tutorial: [Link]
Activity Based Learning (Suggested Activities)/ Practical Based learning
1. Installation of Java (Refer: [Link]
2. Demonstration of online IDEs like geeksforgeeks, jdoodle or any other Tools
3. Demonstration of class diagrams for the class abstraction, type visibility, composition and
Inheritance Assessment Method
● Programming Assignment / Course Project
[Link] a JAVA program to add TWO matrices of suitable order N (The
value of N should be read from command line arguments).
public class MatrixAddition{
public static void main(String[]args){
if([Link]!=1){
3
[Link]("Usage:javaMatrixAddition<N>");
return;
}
int N=[Link](args[0]);
int[][] matrixA=new int[N][N];
int[][] matrixB=new int[N][N];
int[][] resultMatrix=new int[N][N];
fillMatrix(matrixA,N);
fillMatrix(matrixB,N);
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
resultMatrix[i][j]=matrixA[i][j]+matrixB[i][j];
}
}
[Link]("MAtrixA:");
printMatrix(matrixA,N);
[Link]("MAtriB:");
printMatrix(matrixB,N);
[Link]("Sum of matrices of A and B ar:");
printMatrix(resultMatrix,N);
}
private static void fillMatrix(int[][] matrix,int N){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
matrix[i][j]=(int)([Link]()*100);
}
}
}
private static void printMatrix(int[][] matrix,int N){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
[Link](matrix[i][j]+" ");
}
[Link]();
}
[Link]();
}
}
OUTPUT:
Javac [Link]
Java MatrixAddition 2
4
Matrix A:
71 19
77 45
Matrix B:
25 18
20 39
Sum of matrices of A and B are:
96 37
97 84
[Link] a stack class to hold a maximum of 10 integers with suitable methods.
Develop a JAVA main method to illustrate Stack operations.
package prg2;
import [Link];
5
class Stack{
int top;
int s[]=new int[10];
Stack(){
top-=1;
}
void push(int item){
if([Link]-1==top){
[Link]("Stack over folw");
return;
}
else{
top+=1;
s[top]=item;
}
}
void pop(){
if(top==-1){
[Link]("Stack underflow");
return;
}
else{
int item=s[top];
[Link]("item deleted popped :"+item);
top-=1;
}
}
void display(){
if(top==-1){
[Link]("Stack is empty, no item to display");
}
else{
[Link]("Item in stack are:");
for(int i=top;i>=0;i--){
[Link](s[i]);
} } }}
public class Prg2 {
public static void main(String[] args) {
int ch;
Stack stk=new Stack();
Scanner in=new Scanner([Link]);
while(true){
6
[Link]("Stack operation demo");
[Link]("Enter 1:push,2:pop,3:display item,4:exit");
ch=[Link]();
switch(ch){
case 1:
[Link]("Enter the item to be pushed into stack");
int item=[Link]();
[Link](item);
break;
case 2:[Link]();
break;
case 3:
[Link]();
break;
case 4:[Link](0);
default:[Link]("enter the valid choice");
}
}
}
}
OUTPUT:
run:
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
10
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
20
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
30
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
1
Enter the item to be pushed into stack
40
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
2
item deleted popped :40
7
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
3
Item in stack are:
30
20
10
Stack operation demo
Enter 1:push,2:pop,3:display item,4:exit
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 raise
Salary (percent) increases the salary by the given percentage. Develop the
Employee class and suitable main method for demonstration.
class Employeesal{
8
private int id;
private String name;
private double salary;
public Employeesal(int id,Stringname,double salary){
[Link]=id;
[Link]=name;
[Link]=salary;
}
public void raiseSalary(double percent){
if(percent>0){
double raiseAmount=salary*(percent/100);
salary+=raiseAmount;
[Link](name+"'s salary rasied by "+percent+"%.\nNewsalary:$"+salary);
}
else{
[Link]("Invalid [Link] remains unchanged");
}
}
public void EmployeeDetails(){
[Link]("Employee ID "+id+"\nName "+ name+"\nsalary:$"+salary);
}
}
public class Employee{
public static void main(String[] args) {
Employeesal employee=new Employeesal(1,"Vishal",5000);
[Link]("Initial employee deatils:");
[Link]();
[Link](30);
[Link]("Enployee details after raise salary:");
[Link]();
}
}
OUTPUT:
run:
Initial employee deatils:
Employee ID 1
Name Vishal
9
salary:$5000.0
Vishal's salary rasied by 30.0%.
New salary:$6500.0
Enployee details after raise salary:
Employee ID 1
Name Vishal
salary:$6500.0
BUILD SUCCESSFUL (total time: 0 seconds)
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).
10
● 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.
class MyPoint {
private int x;
private int y;
public MyPoint() {
this.x = 0;
this.y = 0;
}
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}
public int[] getXY() {
int[] coordinates = {x, y};
return coordinates;
}
public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}
public double distance(MyPoint another) {
11
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}
public double distance() {
return [Link](x * x + y * y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint point1 = new MyPoint(); // Using default constructor
MyPoint point2 = new MyPoint(3, 4); // Using overloaded constructor
[Link](1, 2);
int[] coordinates = [Link]();
[Link]("Point 1 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")");
[Link]("Distance from Point 1 to (5, 6): " + [Link](5, 6));
[Link]("Distance from Point 1 to Point 2: " + [Link](point2));
[Link]("Distance from Point 1 to the origin: " + [Link]());
[Link]("Point 1: " + point1);
[Link]("Point 2: " + point2);
}
}
OUTPUT:
run:
Point 1 coordinates: (1, 2)
Distance from Point 1 to (5, 6): 5.656854249492381
Distance from Point 1 to Point 2: 2.8284271247461903
Distance from Point 1 to the origin: 2.23606797749979
Point 1: (1, 2)
Point 2: (3, 4)
BUILD SUCCESSFUL (total time: 0 seconds)
[Link] 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
package shapes;
12
class Shape {
public void draw() {
[Link]("Drawing a shape");
}
public void erase() {
[Link]("Erasing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
[Link]("Drawing a circle");
}
@Override
public void erase() {
[Link]("Erasing a circle");
}
}
class Triangle extends Shape {
@Override
public void draw() {
[Link]("Drawing a triangle");
}
@Override
public void erase() {
[Link]("Erasing a triangle");
}
}
class Square extends Shape {
@Override
public void draw() {
[Link]("Drawing a square");
}
@Override
public void erase() {
[Link]("Erasing a square");
}
}
13
public class Shapes {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
for (int i = 0; i<[Link]; i++) {
// Polymorphic method invocation
shapes[i].draw();
shapes[i].erase();
[Link]("------------------------");
}
}
}
OUTPUT:
run:
Drawing a circle
erasing a circle
----------
Drawing a triangle
erasing a triangle
----------
Drawing a square
erasing a square
----------
BUILD SUCCESSFUL (total time: 0 seconds)
6. Develop a JAVA program to create an abstract class Shape with abstract
methods calculateArea() andcalculatePerimeter(). Create subclasses Circle
and Triangle that extend the Shape class and implementthe respective methods
to calculate the area and perimeter of each shape.
package abstractshapes;
14
abstract class Shape_1 {
abstract double calculateArea();
abstract double calculatePerimeter();
}
// Circle subclass
class Circle_1 extends Shape_1 {
private double radius;
// Constructor
public Circle_1(double radius) {
[Link] = radius;
}
@Override
double calculateArea() {
return [Link] * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * [Link] * radius;
}
}
// Triangle subclass
class Triangle_1 extends Shape_1 {
private double side1, side2, side3;
// Constructor
public Triangle_1(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
double calculateArea() {
// Heron's formula for calculating the area of a triangle
double s = (side1 + side2 + side3) / 2;
return [Link](s * (s - side1) * (s - side2) * (s - side));
}
@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
15
}
public class AbstractShapes {
public static void main(String[] args) {
// TODO code application logic here
Circle_1 circle = new Circle_1(5);
[Link]("Circle Area: " + [Link]());
[Link]("Circle Perimeter: " + [Link]());
Triangle_1 triangle = new Triangle_1(3, 4, 5);
[Link]("Triangle Area: " + [Link]());
[Link]("Triangle Perimeter: " + [Link]());
}
OUTPUT:
run:
Cirle Area is 78.53981633974483
Circle Perimeter 31.41592653589793
Triangle Area 6.0
Triangle Perimeter 12.0
BUILD SUCCESSFUL (total time: 0 seconds)
7. Develop a JAVA program to create an interface Resizable with methods resize
Width(int width) and resize Height(int height) that allow an object to be
resized. Create a class Rectangle that implements the Resizable interface and
implements the resize methods.
package testresizable;
16
interface Resizable
{
void resizewidth(int width);
void resizeheight(int height);
}
class Rectangle
{
private int width;
private int height;
public Rectangle(int width,int height)
{
[Link]=width;
[Link]=height;
}
public void resizewidth(int width)
{
[Link]=width;
}
public void resizeheight(int height)
{
[Link]=height;
}
public void display()
{
[Link]("Rectangle width:"+width+",height"+height);
}
}
public class Testresizable{
public static void main(String[] args) {
Rectangle rectangle=new Rectangle(5,10);
[Link]("Orignal display");
[Link]();
[Link](8);
[Link](12);
[Link]("Resize rectangle");
[Link]();
}
}
OUTPUT:
Orignal display
Rectangle width:5,height10
Resize rectangle
17
Rectangle width:8,height12
BUILD SUCCESSFUL (total time: 0 seconds)
8. Develop a JAVA program to create an outer class with a function display.
Create another class inside theouter class named inner with a function called
display and call the two functions in the main class.
package nestedclass;
class Outer
18
{
void display()
{
[Link]("outer class display method");
}
class Inner
{
void display()
{
[Link]("Inner classs display method");
}
}
}
public class NestedClass {
public static void main(String[] args) {
// TODO code application logic here
Outer obj1=new Outer();
[Link]();
[Link] obj2=[Link] Inner();
[Link]();
}
OUTPUT:
run:
outer class display method
Inner classs display method
BUILD SUCCESSFUL (total time: 0 seconds)
9. Develop a JAVA program to raise a custom exception (user defined
exception) for Division By Zero using try, catch, throw and finally.
package exception_divbyzero;
class DivisionByZeroException extends Exception{
public DivisionByZeroException(String message){
19
super(message);
}
}
public class Exception_DivByZero {
public static void main(String[] args) {
int numerator=10;
int denominator=0;
try{
if(denominator==0){
throw new
DivisionByZeroException("divison by zero is not allowed");
}
int remainder=10%0;
[Link]("result of modulus :"+remainder);
int result=numerator/denominator;
[Link]("result of divison :"+result);
}
catch(DivisionByZeroException e){
[Link]("Error :"+[Link]());
}
catch(ArithmeticException e){
[Link]("Error :Dvision by zero occured");
}
finally{
[Link]("Finally block executed");
}
}
}
OUTPUT:
Denominator is 0:
run:
Error :divison by zero is not allowed
Finally block executed
BUILD SUCCESSFUL (total time: 0 seconds)
Denominator is 1:
run:
Error :divison by zero occurred.
Finally block executed
20
BUILD SUCCESSFUL (total time: 0 seconds)
int reminder=10%1
run:
result of modulus :0
result of divison :10
Finally block executed
BUILD SUCCESSFUL (total time: 0 seconds)
10. Develop a JAVA program to create a package named my pack and import &
implement it in a suitable class.
[Link]:
import [Link];
21
public class Mainclass {
public static void main(String[] args)
{
MyPackageClassmyPackageObject=new MyPackageClass();
[Link]();
}
[Link]:
package mypack;
public class MyPackageClass {
public void displayMessage(){
[Link]("THis message isn sent from the myPackageClass inside the mypack package");
}
OUTPUT:
THis message isn sent from the myPackageClass inside the mypack package
BUILD SUCCESSFUL (total time: 0 seconds)
[Link] 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).
package mainthreads_1;
class MyRunnable implements Runnable{
22
@Override
public void run(){
try{
[Link](500);
[Link]("Thread"+[Link]().getId()+"running");
}catch(InterruptedException e){
[Link]();
}
}
}
public class MainThreads_1 {
public static void main(String[] args) {
MyRunnablemyRunnable=new MyRunnable();
Thread thread1=new Thread(myRunnable);
Thread thread2=new Thread(myRunnable);
Thread thread3=new Thread(myRunnable);
[Link]();
[Link]();
[Link]();
OUTPUT:
Thread9running
Thread8running
Thread10running
BUILD SUCCESSFUL (total time: 0 seconds)
[Link] 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);
23
start();
}
public void run(){
for(int i=0;i<=5;i++) {
[Link]("Child Thread:"+i);
try{
[Link](500);
}catch(InterruptedException e){
[Link]("Child Thread is interrupted");
}
}
}
}
public class MainThread {
public static void main(String[] args) {
MyThreadmyThread = new MyThread("Child Thread");
for(int i=0;i<=5;i++){
[Link]("Main Thread:"+i);
try{
[Link](500);
}catch(InterruptedException e) {
[Link]("Main Thread is interrupted");
}
}}
}
OUTPUT:
run:
Main Thread:0
Child Thread:0
Main Thread:1
Child Thread:1
Main Thread:2
Child Thread:2
Main Thread:3
Child Thread:3
Main Thread:4
Child Thread:4
Main Thread:5
Child Thread:5
BUILD SUCCESSFUL (total time: 3 seconds)
24