Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
4K views

Java Lab Manual BCS306A

The document contains a laboratory manual for an Object Oriented Programming with Java course. It includes the course code, teaching hours, credits, objectives, prerequisites, and a list of 6 programming problems or experiments for students to complete. The problems involve developing classes and programs related to concepts like matrices, stacks, inheritance, polymorphism, abstract classes, and interfaces. Students will code solutions in Java and test/demonstrate the programs.

Uploaded by

Soorya Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
4K views

Java Lab Manual BCS306A

The document contains a laboratory manual for an Object Oriented Programming with Java course. It includes the course code, teaching hours, credits, objectives, prerequisites, and a list of 6 programming problems or experiments for students to complete. The problems involve developing classes and programs related to concepts like matrices, stacks, inheritance, polymorphism, abstract classes, and interfaces. Students will code solutions in Java and test/demonstrate the programs.

Uploaded by

Soorya Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

Jnana Sangama, Belagavi-590018

LABORATORY MANUAL

OBJECT ORIENTED PROGRAMMING WITH JAVA / BCS306A

Prepared by,
Dr. Sharanabasavana Gowda, Dr. Sreenatha M, Mr. Vikhyath K B

DEPARTMENT OF COMPUTER SCIENCE ANDENGINEERING

JSS ACADEMY OF TECHNICAL EDUCATION

Bengaluru - 560060
2023-2024
JSS ACADEMY OF TECHNICAL EDUCATION
(Approved by AICTE, New Delhi, Affiliated to Visvesvaraya Technological University, Belagavi, Karnataka, INDIA)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision and Mission of the Institution

Vision
“To be among the finest Institutions providing Engineering and Management Education
empowered with research, innovation and entrepreneurship”

Mission

1. Strive towards Excellence in teaching-learning process and nurture personality


development.
2. Encourage Research, Innovation & Entrepreneurship.
3. Train to uphold highest ethical standards in all activities.

Vision and Mission of the CSE Department

Vision

“To be a distinguished academic and research Department in the field of Computer


Science and Engineering for enabling students to be highly competent professionals to
meet global challenges.”

Mission

1. Impart quality education in Computer Science and Engineering through state-


of-the art learning environment and committed faculty with research
expertise.

2. Train students to become the most sought-after professionals in the field of


Information Technology by providing them strong theoretical foundation
with adequate practical training.

3. Provide a conducive environment for faculty and students to carry out research
and innovation in collaboration with reputed research institutes and industry.

4. Inculcate human values and professional ethics among students to enable them
to become good citizens and serve the society.
JSS ACADEMY OF TECHNICAL EDUCATION
(Approved by AICTE, New Delhi, Affiliated to Visvesvaraya Technological University, Belagavi, Karnataka, INDIA)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Outcomes
a. Engineering Knowledge: Apply knowledge of mathematics, science,
engineering fundamentals and an engineering specialization to the solution of
complex engineering problems.
b. Problem Analysis: Identify, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences
c. Design/ Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet specified needs
with appropriate consideration for public health and safety, cultural, societal and
environmental considerations.
d. Conduct investigations of complex problems using research-based
knowledge and research methods including design of experiments, analysis and
interpretation of data and synthesis of information to provide valid conclusions.
e. Modern Tool Usage: Create, select and apply appropriate techniques, resources
andmodern engineering and IT tools including prediction and modeling to Complex
engineering activities with an under- standing of the limitations.
f. The Engineer and Society: Apply reasoning informed by contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
Consequent responsibilities relevant to professional engineering practice.
g. Environment and Sustainability: Understand the impact of professional
Engineering solutions in societal and environmental contexts and demonstrate
knowledge of and need for sustainable development.
h. Ethics: Apply ethical principles and commit to professional ethics and
Responsibilities and norms of engineering practice.
i. Individual and Team Work: Function effectively as an individual, and as a
member or leader in diverse teams and in multi-disciplinary settings.
j. 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.
k. 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
technological change.
l. Project Management and Finance: Demonstrate knowledge and understanding
of 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 multi-
disciplinary environments.

Program Specific Outcomes

a. PSO1: Apply the principles of Basic Engineering Science to acquire the hardware and
software aspects of Computer Science.
b. PSO2: Solve the real-world problems using modelling for a specific Computer system
and architecture.
c. PSO3: Ability to design and develop applications using various software and hardware
tools.
d. PSO4. Exhibit the practical competence using broad range of programming languages.
List of Experiments

OBJECT ORIENTED PROGRAMMING WITH JAVA

Course Code BCS306A CIE Marks 50


Teaching Hours/Week (L:T:P: S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy 28 Hours of Theory + 2- Total Marks 100
Hours of Practical
Credits 03 Exam Hours 03
Course Objectives:

CLO 1. To learn primitive constructs JAVA programming language.


CLO 2. To understand Object Oriented Programming Features of JAVA.
CLO 3. To gain knowledge on: Packages, Multithreaded programming and exception.

Note: two hours tutorial is suggested for each laboratory sessions.


Prerequisite
• Students should be familiarized about java installation and setting the java
environment.
• Usage of IDEs like Eclipse/Netbeans should be introduced.

Sl. No. PART A – List of problems for which student should develop program and execute in the
Laboratory
Program: Develop a JAVA program to add TWO matrices of suitable order N (The value of N
1 should be read from command line arguments).

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

Program: A class called Employee, which models an employee with an ID, name and salary, is
3 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.
Program: A class called MyPoint which models a 2D point with X and Y coordinates, is designed as
follows:
4 • 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 construct 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 that 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 diatance 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.
Program: Develop a JAVA program to create a class named shape. Create three sub classes namely:
5 circle, triangle and square, each class has two member functions named draw() and erase().
Demonstrate polymorphism concepts by developing suitable methods, defining members data and
main program.
Program: Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeters(). Create subclasses Circle and Triangle that extend the
6 Shape class and implement the respective methods to calculate the area and perimeters of each
shape.
Program: 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
7 implement the Resizable interface and implements the resize methods.

Program: 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
8 functions in the main class.

Program: Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
9
Program: Develop a JAVA program to create a package named mypack and import & implement it
10 in a suitable class.

Program: 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
11 500 milliseconds).
Program: 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
12 be observed that both main thread and created child thread are executed concurrently.

Course Outcome (Course Skill Set)


At the end of the course the student will be able to:

CO 1. Apply the fundamental concepts of object-oriented programming to solve the real-world problems.
CO 2. Apply Java language constructs to implement application programs.
CO 3. Develop applications using inheritance, packages and exception handling features of Java.
CO 4. Apply concepts of multi-threading, auto boxing and enumerations in program development.

Scheme of Continuous Internal Evaluation (CIE):

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). The minimum passing
mark for the SEE is 35% of the maximum marks (18 marks out of 50). 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 Test ( Two Test,
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.

CIE for the practical component of the IPCC

• 15 marks for the conduction of the experiment and preparation of laboratory record, and 10 marks for
the test to be conducted after the completion of all the laboratory sessions.
• On completion of every experiment/program in the laboratory, the student shall be evaluated including
viva-voce and marks shall be awarded on the same day.
• The CIE marks awarded in the case of the practical component shall be based on the continuous
evaluation of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of all
ecperiment’s write-ups are added and scaled down to 15 marks.
• The laboratory test (duration 02/03 hours) after completion of all the experiments shall be conducted for
50 marks and scaled down to 10 marks.
• Scaled-down marks of write-up evaluation and tests added will be CIE marks for the laboratory
component of IPCC for 25 marks.
• The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of the IPCC.

SEE for IPCC

Theory SEE will be conducted by University as per the scheduled timetable, with common question papers for the
course (duration 03 hours)

TEXT BOOKS (TB):

1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021, McGraw-Hill,
ISBN:9781260463422

REFERENCE BOOKS (RB):

1. Programming with Java, 6th Edition, by E Balagurusamy, Mar-2019, McGraw Hill Education,
ISBN:9789353162337
2. Thinking in Java, Fourth Edition, by Bruce Eckel, Prentice Hall, 2006
(https://sd.blackball.lv/library/thinking_in_java_4th_edition.pdf)
OOP with Java /BCS306A

PROGRAM :1

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

PROGRAM:

public class MatrixAddition


{
public static void main(String[] args)
{
// Check if the number of command line arguments is correct
if (args.length != 1)
{
System.out.println("Usage: java MatrixAddition <order N>");
return;
}

// Parse the command line argument to get the order 'N'


int N = Integer.parseInt(args[0]);

// Initialize matrices
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
int[][] result = new int[N][N];

// Input for the first matrix


System.out.println("Enter elements for Matrix 1:");
inputMatrix(matrix1);

// Input for the second matrix


System.out.println("Enter elements for Matrix 2:");
inputMatrix(matrix2);

// Perform matrix addition


addMatrices(matrix1, matrix2, result);

// Display the result


System.out.println("Resultant Matrix after Addition:");
displayMatrix(result);
}

// Function to input elements of a matrix


public static void inputMatrix(int[][] matrix)
{
Scanner scanner = new Scanner(System.in);

for (int i = 0; i < matrix.length; i++)


{
for (int j = 0; j < matrix[0].length; j++)
SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24
1
OOP with Java /BCS306A

{
System.out.print("Enter element at position (" + i + ", " + j + "): ");
matrix[i][j] = scanner.nextInt();
}
}
}

// Function to add two matrices


public static void addMatrices(int[][] matrix1, int[][] matrix2, int[][] result)
{
for (int i = 0; i < matrix1.length; i++)
{
for (int j = 0; j < matrix1[0].length; j++)
{
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to display a matrix


public static void displayMatrix(int[][] matrix)
{
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[0].length; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


2
OOP with Java /BCS306A

PROGRAM :2

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

PROGRAM:

public class Stack


{
private static final int MAX_SIZE = 10;
private int[] stackArray;
private int top;

// Constructor
public Stack()
{
stackArray = new int[MAX_SIZE];
top = -1;
}

// Method to push an element onto the stack


public void push(int element)
{
if (top < MAX_SIZE - 1)
{
stackArray[++top] = element;
System.out.println("Pushed: " + element);
}
else
{
System.out.println("Stack Overflow! Cannot push " + element);
}
}

// Method to pop an element from the stack


public void pop() {
if (top >= 0)
{
int poppedElement = stackArray[top--];
System.out.println("Popped: " + poppedElement);
}
else
{
System.out.println("Stack Underflow! Cannot pop from an empty stack.");
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


3
OOP with Java /BCS306A

// Method to display the elements in the stack


public void display()
{
if (top >= 0)
{
System.out.println("Elements in the Stack:");
for (int i = top; i >= 0; i--)
{
System.out.println(stackArray[i]);
}
}
else
{
System.out.println("Stack is empty.");
}
}

public static void main(String[] args)


{
// Create a stack
Stack myStack = new Stack();

// Perform stack operations


myStack.push(5);
myStack.push(10);
myStack.push(20);
myStack.display();

myStack.pop();
myStack.display();

myStack.push(15);
myStack.push(25);
myStack.push(30);
myStack.display();

myStack.pop();
myStack.pop();
myStack.display();
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


4
OOP with Java /BCS306A
PROGRAM :3

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.

PROGRAM :

public class Employee


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

// Constructor
public Employee(int id, String name, double salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}

// Getter methods
public int getId()
{
return id;
}

public String getName()


{
return name;
}

public double getSalary()


{
return salary;
}

// Method to raise the salary by a given percentage

public void raiseSalary(double percent)


{
if (percent > 0)
{
double increaseAmount = salary * (percent / 100);
salary += increaseAmount;
System.out.println("Salary raised by " + percent + "%. New salary: $" + salary);
}
else
{
SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24
System.out.println("Invalid percentage. Salary remains unchanged.");
5
OOP with Java /BCS306A
}
}

public static void main(String[] args)


{
// Create an Employee object
Employee employee1 = new Employee(101, "John Doe", 50000.0);

// Display initial details


System.out.println("Employee details before raise:");
System.out.println("ID: " + employee1.getId());
System.out.println("Name: " + employee1.getName());
System.out.println("Salary: $" + employee1.getSalary());

// Raise the salary by 10%


employee1.raiseSalary(10);

// Display details after the raise


System.out.println("\nEmployee details after raise:");
System.out.println("ID: " + employee1.getId());
System.out.println("Name: " + employee1.getName());
System.out.println("Salary: $" + employee1.getSalary());
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24

6
OOP with Java /BCS306A

PROGRAM :4

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 construct 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 that
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 diatance 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.

PROGRAM:

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

// Method to set both x and y


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

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


7
OOP with Java /BCS306A

// Method to get x and y in a 2-element int array


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

// Method to get a string description of the instance @Override


public String toString()
{
return "(" + x + ", " + y + ")";
}

// Method to calculate the distance to another point at (x, y)


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

// Overloaded method to calculate the distance to another MyPoint


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

// Another overloaded method to calculate the distance 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 instances of MyPoint
MyPoint point1 = new MyPoint();
MyPoint point2 = new MyPoint(3, 4);

// Display points
System.out.println("Point 1: " + point1.toString());
System.out.println("Point 2: " + point2.toString());

// Set new coordinates for point1


point1.setXY(1, 2);

// Display updated point1


System.out.println("Point 1 (after setXY): " + point1.toString());

// Get coordinates of point1


int[] coordinates = point1.getXY();
SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24
8
OOP with Java /BCS306A

System.out.println("Coordinates of Point 1: (" + coordinates[0] + ", " + coordinates[1] + ")");

// Calculate distance between point1 and point2


double distance1 = point1.distance(point2);
System.out.println("Distance between Point 1 and Point 2: " + distance1);

// Calculate distance of point1 to the origin


double distance2 = point1.distance();
System.out.println("Distance from Point 1 to the Origin: " + distance2);
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


9
OOP with Java /BCS306A

PROGRAM :5

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(). Demonstarte
polymorphism concepts by developing suitable methods, defining members data and main
program.

PROGRAM:

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

public void erase()


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

class Circle extends Shape


{
// Override draw method for Circle @Override

public void draw()


{
System.out.println("Drawing a circle");
}

// Override erase method for Circle


@Override

public void erase()


{
System.out.println("Erasing a circle");
}
}

class Triangle extends Shape


{
// Override draw method for Triangle
@Override

public void draw()


{
System.out.println("Drawing a triangle");

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


10
OOP with Java /BCS306A

// Override erase method for Triangle


@Override

public void erase()


{
System.out.println("Erasing a triangle");
}
}

Class Square extends Shape


{
// Override draw method for Square
@Override

public void draw()


{
System.out.println("Drawing a square");
}

// Override erase method for Square


@Override

public void erase()


{
System.out.println("Erasing a square");
}
}

public class TestShapes {


public static void main(String[] args) {
// Create an array of Shape objects

Shape[] shapes = new Shape[3];


shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();

// Demonstrate polymorphism
for (Shape shape : shapes)
{
shape.draw();
shape.erase();
System.out.println(); // Add a newline for clarity
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


11
OOP with Java /BCS306A

PROGRAM :6

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

PROGRAM:

abstract class Shape


{
// Abstract methods
public abstract double calculateArea();
public abstract double calculatePerimeter();
}

class Circle extends Shape


{
private double radius;

// Constructor
public Circle(double radius)
{
this.radius = radius;
}

// Implement abstract methods


@Override

public double calculateArea()


{
return Math.PI * radius * radius;
}

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

class Triangle extends Shape


{
private double side1;
private double side2;
private double side3;

// Constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


12
OOP with Java /BCS306A

this.side3 = side3;
}

// Implement abstract methods


@Override

public double calculateArea()


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

@Override

public double calculatePerimeter()


{
return side1 + side2 + side3;
}
}

public class TestShapes


{
public static void main(String[] args)
{
// Create instances of Circle and Triangle
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);

// Display area and perimeter for Circle


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

// Display area and perimeter for Triangle


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

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


13
OOP with Java /BCS306A

PROGRAM :7

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
implement the Resizable inteeface and implements the resize methods.

PROGRAM:

// Define the Resizable interface


interface Resizable
{
void resizeWidth(int width);
void resizeHeight(int height);
}

// Implement the Resizable interface in the Rectangle class


class Rectangle implements Resizable
{
private int width;
private int height;

// Constructor
public Rectangle(int width, int height)
{
this.width = width;
this.height = height;
}

// Implement resizeWidth method


@Override

public void resizeWidth(int width)


{
this.width = width;
System.out.println("Width resized to: " + width);
}

// Implement resizeHeight method


@Override

public void resizeHeight(int height)


{
this.height = height;
System.out.println("Height resized to: " + height);
}

// Display the current dimensions of the rectangle


SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24
14
OOP with Java /BCS306A

public void displayDimensions()


{
System.out.println("Rectangle Dimensions - Width: " + width + ", Height: " + height);
}
}

public class TestResizable


{
public static void main(String[] args)
{
// Create an instance of Rectangle
Rectangle rectangle = new Rectangle(10, 5);

// Display the initial dimensions


System.out.println("Initial Dimensions:");
rectangle.displayDimensions();

// Resize the width and height


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

// Display the dimensions after resizing


System.out.println("\nDimensions After Resizing:");
rectangle.displayDimensions();
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


15
OOP with Java /BCS306A

PROGRAM :8

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.

PROGRAM:

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

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

public class MainClass


{
public static void main(String[] args)
{
// Create an instance of the outer class
Outer outer = new Outer();

// Call the display method of the outer class


outer.display();

// Create an instance of the inner class using the outer class instance
Outer.Inner inner = outer.new Inner();

// Call the display method of the inner class


inner.display();
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


16
OOP with Java /BCS306A
PROGRAM :9

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

PROGRAM:

// Custom exception class


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

public class CustomExceptionExample


{
public static void main(String[] args)
{
try
{

// Perform division operation that might result in division by zero


int numerator = 10;
int denominator = 0;

// Check if the denominator is zero


if (denominator == 0)
{
throw new DivisionByZeroException("Division by zero is not allowed");
}

int result = numerator / denominator;


System.out.println("Result of the division: " + result);
}
catch (DivisionByZeroException e)
{
// Handle the custom exception
System.out.println("Error: " + e.getMessage());
}
catch (ArithmeticException e)
{
// Handle the regular ArithmeticException (e.g., if the denominator is zero)

System.out.println("Error: " + e.getMessage());


}
finally
{

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24

17
OOP with Java /BCS306A

// This block is always executed, regardless of whether an exception is thrown or not


System.out.println("Finally block executed");
}
}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24

18
OOP with Java /BCS306A

PROGRAM :10

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

PROGRAM:

Create the mypack package:


Create a directory named mypack. Inside it, create a Java file named MyClass.java:

// mypack/MyClass.java
package mypack;

public class MyClass


{
public void displayMessage()
{
System.out.println("Hello from mypack.MyClass!");
}
}

Create a class that imports and uses MyClass:


Now, create another class in a different directory (let's call it MainClass):

// MainClass.java
import mypack.MyClass;

public class MainClass


{
public static void main(String[] args)
{
// Create an instance of MyClass from the mypack package
MyClass myObject = new MyClass();

// Call the displayMessage method from MyClass


myObject.displayMessage();
}
}

Ensure that both files are in separate directories, and the MainClass.java file is not inside the mypack
directory.

Now, compile and run the MainClass:

javac MainClass.java
java MainClass

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


19
OOP with Java /BCS306A

PROGRAM :11

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

PROGRAM:

class MyRunnable implements Runnable


{
private String threadName;

public MyRunnable(String name)


{
this.threadName = name;
}

@Override
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(threadName + ": Count - " + i);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(threadName + " thread interrupted.");
}
System.out.println(threadName + " thread exiting.");
}
}

public class RunnableThreadExample


{
public static void main(String[] args)
{
// Create instances of MyRunnable
MyRunnable runnable1 = new MyRunnable("Thread 1");
MyRunnable runnable2 = new MyRunnable("Thread 2");

// Create threads and associate them with the runnable instances


Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24

20
OOP with Java /BCS306A
// Start the threads
thread1.start();
thread2.start();

// Main thread
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: Count - " + i);
try
{
// Sleep for 500 milliseconds
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
}

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


}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24

21
OOP with Java /BCS306A

PROGRAM :12

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.

PROGRAM:

class MyThread extends Thread


{
public MyThread(String threadName)
{
// Call the base class constructor
super(threadName);
// Start the thread
start();
}

@Override

public void run()


{
try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(Thread.currentThread().getName() + ": Count - " + i);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + " thread interrupted.");
}

System.out.println(Thread.currentThread().getName() + " thread exiting.");


}
}

public class ThreadExample


{
public static void main(String[] args)
{
// Create an instance of MyThread
MyThread myThread = new MyThread("Child Thread");

// Main thread

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


22
OOP with Java /BCS306A

try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(Thread.currentThread().getName() + ": Count - " + i);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + " thread interrupted.");
}

System.out.println(Thread.currentThread().getName() + " thread exiting.");


}
}

SBG, SM, VKB, Dept. of CSE, JSSATEB 2023-24


23

You might also like