0% found this document useful (0 votes)
154 views72 pages

Oops With Java Lab Manual - 2024

oops with java

Uploaded by

Sathvik Mv
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)
154 views72 pages

Oops With Java Lab Manual - 2024

oops with java

Uploaded by

Sathvik Mv
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

RV Institute of Technology and Management®

RV Educational Institutions®
RV Institute of Technology and Management
(Affiliated to VTU, Belagavi)
JP Nagar 8th Phase, Bengaluru - 560076

Department of
Information Science and Engineering

LAB MANUAL
Course Name : Object Oriented Programming with Java Lab

Course Code : BCS306A


III Semester
2022 Scheme

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 1


RV Institute of Technology and Management®

CONTENTS

Sl No Particulars Page No

1 Syllabus 6
2 Introduction To Object Oriented Programming 7
Overview of Java 8
Program 1:
3 13
Develop a JAVA program to add TWO matrices of suitable order N
(The value of N should be read from command line arguments).
Program 2:
4 Develop a stack class to hold a maximum of 10 integers with suitable 17
methods. Develop a JAVA main method to illustrate Stack
operations.
Program 3:
A class called Employee, which models an employee with an ID,
5 name and salary, is designed as shown in the following class 21
diagram. The method raiseSalary (percent) increases the salary by
the given percentage. Develop the Employee class and suitable main
method for demonstration.
Program 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.
6 23
• 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)

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 2


RV Institute of Technology and Management®

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

Program 5:
Develop a JAVA program to create a class named shape. Create three
7 sub classes namely: circle, triangle and square, each class has two 29
member functions named draw () and erase (). Demonstrate
polymorphism concepts by developing suitable methods, defining
member data and main program.
Program 6:
Develop a JAVA program to create an abstract class Shape with
8 abstract methods calculateArea() and calculatePerimeter(). Create 32
subclasses Circle and Triangle that extend the Shape class and
implement the respective methods to calculate the area and perimeter
of each shape.
Program 7:
Develop a JAVA program to create an interface Resizable with
9 methods resizeWidth(int width) and resizeHeight(int height) that 35
allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize
methods
Program 8:
10 Develop a JAVA program to create an outer class with a function 39
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 9:
11 42
Develop a JAVA program to raise a custom exception (user defined
exception) for DivisionByZero using try, catch, throw and finally.
Program 10:
12 45
Develop a JAVA program to create a package named mypack and
import & implement it in a suitable class.
Program 11:
Write a program to illustrate creation of threads using runnable class.
13 48
(start method start each of the newly created thread. Inside the run
method there is sleep() for suspend the thread for 500 milliseconds).

14 Program 12: 52

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 3


RV Institute of Technology and Management®

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
Programs beyond the syllabus

Program 13:
15 Create a multi-threaded banking system where multiple customers can
deposit and withdraw money from their accounts concurrently while
maintaining data consistency.

Program 14:
Create a custom exception class called "ProductAddException" that
extends the standard Java "Exception" class.

Write a program that allows users to add products to the inventory.


Implement exception handling to catch and handle the following
scenarios:
16 If the user tries to add a product with a negative price, throw a
"ProductAddException" with an appropriate error message.

If the user tries to add a product with a quantity less than 0, throw a
"ProductAddException" with a suitable error message.

Ensure that the program gracefully handles any other exceptions that
may occur during the product addition process.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 4


RV Institute of Technology and Management®

OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY


(Effective from the academic year 2022 -2023)
SEMESTER – III
Course Code: BCS306A CIE Marks 50
Number of Contact Hours/Week 2:0:2
Total Hours of Pedagogy 20 Exam Hours 03

Course Learning Objectives:


This course (21CSL35) will enable students to:
• Demonstrate the use of Eclipse / Netbeans IDE to create Java Applications.
• Using java programming to develop programs for solving real-world problems.
• Reinforce the understanding of basic object-oriented programming concepts.

Course Description
• 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 students 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 experiments’ 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 evaluations 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.

Programs List:
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.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 5


RV Institute of Technology and Management®

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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 6


RV Institute of Technology and Management®

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

Laboratory Outcomes:
The student should be able to:
• Use Eclipse/NetBeans IDE to design, develop, debug Java Projects.
• Analyze the necessity for Object Oriented Programming paradigm over structured
programming and become familiar with the fundamental concepts in OOP.
• Demonstrate the ability to design and develop java programs, analyze, and interpret
object-oriented data and document results.
• Apply the concepts of multiprogramming, exception/event handling, abstraction to
develop robust programs.
• Develop user friendly applications using File I/O and GUI concepts.

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.

Continuous Internal Evaluation (CIE):


CIE for the practical component of the IPCC:
CIE marks for the practical course is 25 Marks.
● 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 students 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 experiments’ 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.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 7


RV Institute of Technology and Management®

● Scaled-down marks of write-up evaluations 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.

Semester End Evaluation (SEE):


• The practical portion will have a CIE component only.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 8


RV Institute of Technology and Management®

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Object-oriented programming (OOP)


Object-oriented programming (OOP) is a computer programming model that organizes
software design around data, or objects, rather than functions and logic. An object can be
defined as a data field that has unique attributes and behavior.

Structure of object-oriented programming


The structure, or building blocks, of object-oriented programming include the following:

• Classes are user-defined data types that act as the blueprint for individual objects, attributes
and methods.
• Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or an abstract entity. When class is defined initially, the
description is the only object that is defined.
• Methods are functions that are defined inside a class that describe the behaviors of an
object. Each method contained in class definitions starts with a reference to an instance
object. Additionally, the subroutines contained in an object are called instance methods.
Programmers use methods for reusability or keeping functionality encapsulated inside one
object at a time

Principles of Object-Oriented Programming


Object-oriented programming is based on the following principles:

Encapsulation: This principle states that all important information is contained inside an
object and only select information is exposed. The implementation and state of each object are
privately held inside a defined class. Other objects do not have access to this class or the
authority to make changes. They are only able to call a list of public functions or methods. This
characteristic of data hiding provides greater program security and avoids unintended data
corruption.

Abstraction: Objects only reveal internal mechanisms that are relevant for the use of other
objects, hiding any unnecessary implementation code. The derived class can have its
functionality extended. This concept can help developers more easily make additional changes
or additions over time.

Inheritance: Classes can reuse code from other classes. Relationships and subclasses between
objects can be assigned, enabling developers to reuse common logic while still maintaining a
unique hierarchy. This property of OOP forces a more thorough data analysis, reduces
development time and ensures a higher level of accuracy.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 9


RV Institute of Technology and Management®

Polymorphism: Objects are designed to share behaviors and they can take on more than one
form. The program will determine which meaning or usage is necessary for each execution of
that object from a parent class, reducing the need to duplicate code. A child class is then created,
which extends the functionality of the parent class. Polymorphism allows different types of
objects to pass through the same interface.

Object-oriented programming languages


• C++
• Java
• Python

Overview of Java
Java Is Important to the Internet, The Internet helped catapult Java to the forefront of
programming, and Java, in turn, has had a profound effect on the Internet. The reason for this
is quite simple: Java expands the universe of objects that can move about freely in cyberspace.
In a network, two very broad categories of objects are transmitted between the server and our
personal computer: passive information and dynamic, active programs.

Features of JAVA
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 10


RV Institute of Technology and Management®

Eclipse IDE
In the context of computing, Eclipse is an integrated development environment (IDE) for
developing applications using the Java programming language and other programming
languages such as C/C++, Python, PERL, Ruby etc. The Eclipse platform which provides the
foundation for the Eclipse IDE is composed of plug-ins and is designed to be extensible using
additional plug-ins. Developed using Java, the Eclipse platform can be used to develop rich
client applications, integrated development environments and other tools. Eclipse can be used
as an IDE for any programming language for which a plug-in is available.

Steps involved to create a new project in eclipse environment


This step will show you how to create a Java application project in Eclipse.
1) Choose File → New → Java Project from the Eclipse menu bar, as in the following
example:
2) Enter "Test" as the project name. Keep rest of the settings

Click "Finish" button and Eclipse IDE will generate the java project automatically
Right click on 'src' folder and select from context menu New --> Class.
Write "Test" in the 'Name' field and select the check-box for 'public static void main(String[]
args)'.
Click "Finish" button. Eclipse will generate a java class and open the same in the java editor
Right click on 'test.java' and select from context menu 'Run As' --> 'Java Application'.
Your code will print related output in the eclipse console.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 11


RV Institute of Technology and Management®

Lab Programs

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

Command-Line Arguments: Command-line arguments are values provided to a program


when it's executed. In this program, the value of N is a command-line argument, and it's read
using args[0].
2D Arrays: In Java, a 2D array is an array of arrays. In this program, matrixA, matrixB, and
result are 2D arrays, where each element is accessed using two indices (i and j).
Matrix Addition: Matrix addition is a mathematical operation where corresponding elements
of two matrices are added together to produce a new matrix. It follows the rule that matrices
must have the same dimensions for addition to be possible.
Nested Loops: Nested loops are used to iterate over the elements of a 2D array. In this program,
nested loops are used to traverse the rows and columns of the matrices for both filling and
adding.
Functions: Functions (methods) are used to encapsulate specific tasks. In this program,
functions like fillMatrix, addMatrices, and printMatrix help organize the code and make it more
readable and reusable.
Code:
public class MatrixAddition {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java MatrixAddition N");
System.exit(1);
}

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

if (N <= 0) {
System.out.println("N must be a positive integer.");
System.exit(1);
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 12


RV Institute of Technology and Management®

int[][] matrixA = new int[N][N];


int[][] matrixB = new int[N][N];
int[][] result = new int[N][N];

// Fill matrixA and matrixB with values (you can modify this part)
fillMatrix(matrixA, N);
fillMatrix(matrixB, N);

// Add the matrices


addMatrices(matrixA, matrixB, result, N);

// Display the matrices


System.out.println("Matrix A:");
printMatrix(matrixA);

System.out.println("Matrix B:");
printMatrix(matrixB);

System.out.println("Result of Matrix Addition:");


printMatrix(result);
}

// Fill a matrix with random values (you can modify this part)
public static void fillMatrix(int[][] matrix, int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = i + j; // You can change this to your desired values
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 13


RV Institute of Technology and Management®

}
}

// Add two matrices


public static void addMatrices(int[][] A, int[][] B, int[][] result, int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
}

// Print a matrix
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 14


RV Institute of Technology and Management®

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 15


RV Institute of Technology and Management®

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

A stack is a fundamental data structure in computer science and programming that follows the
Last-In, First-Out (LIFO) principle. It's a collection of elements with two primary operations:
push and pop. Stacks are often implemented with arrays or linked lists.

Here are the key operations associated with a stack:

Push: This operation adds an element to the top of the stack. It's like placing an item on top of
a stack of books.

Pop: This operation removes the top element from the stack. You can think of it as taking the
top book off the stack.

Peek or Top: This operation retrieves the top element without removing it from the stack. It's
like looking at the top book without taking it off.

IsEmpty: This operation checks if the stack is empty. If there are no elements in the stack, it
returns true; otherwise, it returns false.

Stacks are often used in situations where you need to maintain a last-in, first-out order. Some
common use cases for stacks include:

Function Call Stack: In many programming languages, function calls are managed using a
stack. When a function is called, its information is pushed onto the stack, and when it returns,
it's popped off the stack.

Undo/Redo Functionality: Stacks are used to implement undo and redo operations in software
applications. Each change is pushed onto the stack, and undo pops the most recent change off
the stack.

Expression Evaluation: Stacks can be used to evaluate expressions in reverse Polish notation
(postfix notation). Operators and operands are pushed and popped as the expression is
processed.

Backtracking: Stacks are helpful for backtracking algorithms, such as depth-first search in
graph traversal.

Code:
class Stack {
private int maxSize = 10;
private int top;
private int[] stackArray;

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 16


RV Institute of Technology and Management®

public Stack() {
stackArray = new int[maxSize];
top = -1; // Initialize the top of the stack
}

public void push(int item) {


if (top < maxSize - 1) {
stackArray[++top] = item;
System.out.println("Pushed: " + item);
} else {
System.out.println("Stack is full. Cannot push " + item);
}
}

public int pop() {


if (top >= 0) {
int item = stackArray[top--];
System.out.println("Popped: " + item);
return item;
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1; // Indicate an empty stack
}
}

public void display() {


System.out.print("Stack: ");
for (int i = 0; i <= top; i++) {

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 17


RV Institute of Technology and Management®

System.out.print(stackArray[i] + " ");


}
System.out.println();
}
}

public class StackExample {


public static void main(String[] args) {
Stack stack = new Stack();

stack.push(5);
stack.push(10);
stack.push(15);

stack.display();

int poppedItem = stack.pop();


if (poppedItem != -1) {
System.out.println("Popped item: " + poppedItem);
}

stack.display();

stack.push(20);
stack.push(25);

stack.display();
}
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 18


RV Institute of Technology and Management®

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 19


RV Institute of Technology and Management®

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.

Code:
import java.text.NumberFormat;
import java.util.Locale;

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


if (percent > 0) {
double raiseAmount = (percent / 100) * salary;
salary += raiseAmount;
}
}

public void displayEmployeeDetails() {


System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 20


RV Institute of Technology and Management®

NumberFormat indianCurrencyFormat = NumberFormat.getCurrencyInstance(new


Locale("en", "IN"));
System.out.println("Employee Salary: " + indianCurrencyFormat.format(salary));
}

public static void main(String[] args) {


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

// Display initial employee details


System.out.println("Initial Employee Details:");
emp1.displayEmployeeDetails();

// Give the employee a 10% raise


emp1.raiseSalary(10);

// Display updated employee details


System.out.println("\nEmployee Details After Raise:");
emp1.displayEmployeeDetails();
}
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 21


RV Institute of Technology and Management®

Output:

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.

A default constructor is a constructor in a class that is automatically provided by the


programming language if you don't explicitly define any constructors for that class. It is also
sometimes called a "no-argument constructor" or "zero-argument constructor." Default
constructors do not accept any arguments, and they typically initialize the object's attributes to
default or initial values.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 22


RV Institute of Technology and Management®

Here are some key points about default constructors:


Automatic Generation: If you don't provide any constructors in your class, the programming
language (such as Java or C++) will automatically generate a default constructor for you.
No Arguments: A default constructor takes no arguments. It has an empty parameter list, like
this: ClassName() { /* constructor code */ }.
Initialization: In the absence of user-defined constructors, the default constructor initializes
object attributes to their default values. For numeric types (e.g., int, double), this is often 0, and
for reference types (e.g., objects), it's typically null.
Overriding: If you define any constructors with arguments in a class, the language will not
automatically generate a default constructor. In this case, you can still define your own default
constructor explicitly if needed.
Use Cases: Default constructors are useful when you want to create objects without specifying
initial values for their attributes, or when you want to rely on the default initialization behavior.
Method overloading is a feature in object-oriented programming languages (such as Java, C++,
and C#) that allows you to define multiple methods in a class with the same name but different
parameters. These methods can have different numbers or types of parameters, and the
appropriate method to call is determined by the number and types of arguments passed to it at
the time of invocation. Method overloading is based on the concept of polymorphism and
provides several advantages, including code reusability and improved readability.
Here are the key characteristics and benefits of method overloading:
Same Method Name: In method overloading, multiple methods in the same class share the
same name.
Different Parameters: Overloaded methods have different parameter lists. This can involve a
different number of parameters or parameters of different types or both.
Compile-Time Polymorphism: The choice of which overloaded method to call is determined
at compile time based on the arguments provided. This is also known as "compile-time
polymorphism" or "static polymorphism."
Improved Readability: Overloading allows you to use the same method name for operations
that are conceptually related, making the code more readable. For example, you can have a
method calculateArea that is overloaded to handle different shapes (e.g., circles, rectangles,
triangles).
Default Parameters: Method overloading can be used to provide default values for parameters.
For example, you can have a method that accepts fewer arguments by providing default values
for the missing parameters.

Code:
class MyPoint {

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 23


RV Institute of Technology and Management®

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

public void setXY(int x, int y) {


this.x = x;
this.y = y;
}

public int[] getXY() {


int[] coordinates = {x, y};
return coordinates;
}

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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 24


RV Institute of Technology and Management®

public double distance(int x, int y) {


int dx = this.x - x;
int dy = this.y - y;
return Math.sqrt(dx * dx + dy * dy);
}

public double distance(MyPoint another) {


return distance(another.x, another.y);
}

public double distance() {


return distance(0, 0);
}
}

public class TestMyPoint {


public static void main(String[] args) {
MyPoint point1 = new MyPoint(); // Default constructor (0, 0)
MyPoint point2 = new MyPoint(3, 4); // Overloaded constructor (3, 4)

// Testing setXY and getXY methods


point1.setXY(1, 2);

// Display point1's coordinates


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

// Testing distance methods


double distance1 = point1.distance(point2); // Distance between point1 and point2

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 25


RV Institute of Technology and Management®

double distance2 = point1.distance(); // Distance between point1 and the origin (0,0)

System.out.println("Distance between Point 1 and Point 2: " + distance1);


System.out.println("Distance between Point 1 and the origin: " + distance2);
}
}

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 26


RV Institute of Technology and Management®

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 27


RV Institute of Technology and Management®

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.
Polymorphism is one of the fundamental concepts in object-oriented programming (OOP)
and plays a crucial role in designing and implementing flexible and extensible software. It
allows objects of different classes to be treated as objects of a common superclass, and it
enables you to create more generic and flexible code.
Polymorphism:
"Polymorphism" is derived from two Greek words: "poly," meaning many, and "morph,"
meaning form. In the context of OOP, polymorphism means "many forms."
Polymorphism allows objects of different classes to be treated as objects of a common
superclass or interface. This promotes code reusability and flexibility.
Method Overriding:
Polymorphism is often achieved through method overriding. In a subclass, you can provide a
specific implementation of a method that is already defined in a superclass. This allows you to
customize the behavior of the method for the subclass.
Dynamic Binding:
One of the key features of polymorphism is dynamic method binding. This means that the
decision about which method to call is made at runtime, based on the actual type of the object
rather than the reference type.
This enables the code to work with objects of different subclasses using a common interface or
superclass, and the appropriate method implementation is selected at runtime.

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

public void erase() {


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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 28


RV Institute of Technology and Management®

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

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

class Square extends Shape {


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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 29


RV Institute of Technology and Management®

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

public class Main {


public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
for (Shape shape : shapes) {
shape.draw();
shape.erase();
System.out.println();
}
}
}

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 30


RV Institute of Technology and Management®

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 31


RV Institute of Technology and Management®

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.
In Java, an abstract class and abstract methods are used to define a blueprint for other
classes. They are crucial concepts in object-oriented programming and are often used when
you want to create a common interface for a group of related classes while ensuring that certain
methods are implemented by each subclass. Here's an explanation of abstract classes and
abstract methods:

Abstract Class:
An abstract class is a class that cannot be instantiated on its own. It serves as a blueprint for
other classes and may contain both regular (concrete) methods and abstract methods.
Abstract classes are declared using the abstract keyword in Java.
They can have constructors, instance variables, and regular methods just like any other class.
Abstract classes are typically used when you want to create a common base class for a group
of related subclasses, and you want to ensure that certain methods are implemented in those
subclasses.

Abstract Method:
An abstract method is a method declared in an abstract class but doesn't have a method body
(implementation). It's defined with the abstract keyword and followed by a method signature
and a semicolon, but without curly braces.
Subclasses of an abstract class must provide concrete (implemented) versions of all the abstract
methods declared in the superclass. This is a way to enforce that certain behavior must be
defined in subclasses.
Abstract methods are declared in the abstract class to specify what each subclass should
implement, but the actual implementation details are left to the subclasses.
Abstract methods are often used when you have a method that should be implemented
differently in each subclass, but you want to ensure that it's present in each subclass.

Code:
abstract class Shape {
// Abstract method to calculate the area
public abstract double calculateArea();

// Abstract method to calculate the perimeter


public abstract double calculatePerimeter();

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 32


RV Institute of Technology and Management®

class Circle extends Shape {


private double radius;

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

@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;
this.side3 = side3;
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 33


RV Institute of Technology and Management®

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

@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Circle - Area: " + circle.calculateArea());
System.out.println("Circle - Perimeter: " + circle.calculatePerimeter());

Triangle triangle = new Triangle(3.0, 4.0, 5.0);


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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 34


RV Institute of Technology and Management®

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
The concept of an interface in programming is a fundamental principle, not limited to just
Java but prevalent in various object-oriented programming languages like Java, C#, and
others. It serves as a way to define a contract or a set of rules that classes must adhere to.
Here's an explanation of the concept of interfaces:
Contractual Obligation:
An interface defines a contract that a class must adhere to. It specifies a set of methods that
any class implementing the interface must provide. Think of it as a promise that a class
makes to provide certain functionality.
Method Signatures, No Implementation:
An interface contains method signatures (i.e., the name, return type, and parameters of
methods) but doesn't contain the implementation of those methods. It only defines what
methods should be present in any class that implements it.
Multiple Inheritance:
Interfaces allow a form of multiple inheritance. A class can implement multiple interfaces,
which means it can inherit the method signatures of multiple interfaces. This is valuable for
sharing functionality across different classes.
Polymorphism and Abstraction:
Interfaces promote polymorphism, which allows objects of different classes to be treated as
objects of a common interface type. This enhances code flexibility and reusability.
Interfaces also provide a high level of abstraction, allowing you to define functionality at a
conceptual level without specifying implementation details.
Separation of Concerns:
Interfaces separate the definition of a contract from the implementation. This separation is
crucial in large software systems where different teams or individuals may work on the
interface and the classes implementing it independently.
Code Reusability:
Interfaces facilitate code reusability because classes that implement an interface can provide
their own specific implementations of the required methods while adhering to the same
contract.
Testing and Mocking:
Interfaces are useful in testing, as you can create mock objects that implement the same
interface as the real objects. This allows for easier testing of different parts of a system.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 35


RV Institute of Technology and Management®

Design by Contract:
Interfaces are a way to apply the "Design by Contract" principle, which emphasizes that classes
should adhere to a specific contract in terms of behavior.
Encapsulation:
Interfaces help in encapsulation by providing a clear and well-defined way to interact with
objects.
In summary, the concept of an interface in programming is a powerful way to define a contract
for classes. It promotes flexibility, code reusability, polymorphism, and separation of concerns
in software development. By adhering to these contracts, classes can interact with one another
and share functionality in a structured and predictable way.

Code:
// Define the Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Create a class Rectangle that implements the Resizable interface


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

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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 36


RV Institute of Technology and Management®

// Implementation of the resizeWidth method


@Override
public void resizeWidth(int newWidth) {
width = newWidth;
}

// Implementation of the resizeHeight method


@Override
public void resizeHeight(int newHeight) {
height = newHeight;
}

// Method to display the current dimensions


public void displayDimensions() {
System.out.println("Width: " + width);
System.out.println("Height: " + height);
}
}

public class Main {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 7);
System.out.println("Original Dimensions:");
rectangle.displayDimensions();

// Resizing the rectangle


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

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 37


RV Institute of Technology and Management®

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

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 38


RV Institute of Technology and Management®

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.
Nested Classes:
In Java, you can define a class within another class. The class defined within is referred to as a
"nested class" or an "inner class."
Inner classes are used to logically group classes that are only used in one place, to increase
encapsulation, and to control access.
Outer Class:
In the program, the Outer class is the "outer" class that contains the Inner class. It also has a
display method.
Inner Class:
The Inner class is an "inner" class defined within the Outer class. It also has a display method.
It can access the members of the outer class, including private members.
Accessing Inner Class:
To create an instance of the inner class, you need to use the outer class instance. In the main
method, Outer.Inner innerObj = outerObj.new Inner(); demonstrates how to create an inner
class object using an outer class object.
Method Overriding:
Both the outer and inner classes have a method named display. This demonstrates the concept
of method overriding. The inner class's display method effectively overrides the outer class's
display method.
Method Invocation:
• The program shows how to call the display methods of both the outer and inner classes.
• When you call outerObj.display(), it invokes the display method of the outer class.
• When you call innerObj.display(), it invokes the display method of the inner class.
Namespace Separation:
Inner classes can provide a way to logically group related functionality and separate their
names from the outer class. This can help avoid naming conflicts and improve code
organization.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 39


RV Institute of Technology and Management®

Code:
class Outer {
void display() {
System.out.println("This is the outer class's display method.");
}

class Inner {
void display() {
System.out.println("This is the inner class's display method.");
}
}
}

public class Main {


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

// Calling the outer class's display method


outerObj.display();

// Calling the inner class's display method


innerObj.display();
}
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 40


RV Institute of Technology and Management®

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 41


RV Institute of Technology and Management®

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

Exception:
An exception is an abnormal or unexpected event or condition that occurs during the execution
of a program and disrupts the normal flow of the program.
Exceptions can represent various types of errors or problems, such as division by zero, file not
found, invalid input, or network connection issues.
Types of Exceptions:
Exceptions are typically categorized into two types: checked exceptions and unchecked
exceptions.
Checked exceptions are exceptions that must be either caught (using try-catch) or declared
(using throws) by the code that calls a method that might throw the exception. Examples
include IOException.
Unchecked exceptions (also known as runtime exceptions) are exceptions that do not have to
be explicitly handled. They usually indicate programming errors, such as NullPointerException
or ArrayIndexOutOfBoundsException.
Exception Handling:
Exception handling is a mechanism provided by programming languages to gracefully and
safely deal with exceptions when they occur.
It allows you to specify what should happen when an exception is encountered, such as
providing alternative actions, logging the error, or displaying a meaningful error message.
The try-catch Block:
The most common way to handle exceptions is by using a try-catch block. Within the try block,
you enclose code that might throw an exception. In the catch block, you define how to handle
the exception if one is thrown.
If an exception occurs within the try block, the program immediately transfers control to the
appropriate catch block.
The throws Keyword:
The throws keyword is used to declare that a method might throw a specific exception. When
a method declares an exception using throws, it is essentially saying, "I might have a problem,
and I'm not handling it here; I'm passing the responsibility to the caller."
The calling method must either handle the exception using a try-catch block or declare the
exception using throws in its own method signature.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 42


RV Institute of Technology and Management®

The finally Block:


The finally block is used to specify a block of code that is guaranteed to be executed, regardless
of whether an exception occurs or not. It's often used for cleanup actions like closing resources.
Custom Exceptions:
In addition to built-in exceptions, you can create custom exceptions by extending the Exception
class. This allows you to handle application-specific errors in a structured way.

Code:
// 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) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}

int result = numerator / denominator;


System.out.println("Result: " + result);
} catch (DivisionByZeroException e) {
System.err.println("Caught Custom Exception: " + e.getMessage());
} catch (ArithmeticException e) {

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 43


RV Institute of Technology and Management®

System.err.println("Caught ArithmeticException: " + e.getMessage());


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

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 44


RV Institute of Technology and Management®

10) Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
Packages:
In programming, a package is a way to organize related classes and interfaces into a single
namespace. It provides a structured mechanism for grouping classes, which makes it easier to
manage and maintain your code. Here are the key concepts related to packages:

Namespace Organization:
Packages are used to organize classes, interfaces, and other related elements into separate
namespaces.
A package is like a directory or folder that contains related classes. It helps avoid naming
conflicts by keeping classes with the same name separate.
Access Control:
Packages also provide a level of access control. You can use the public, protected, or default
(no modifier) access modifiers to control the visibility of classes and their members within the
same package or in other packages.
Hierarchical Structure:
Packages can have a hierarchical structure, which means you can have sub-packages within
packages. For example, com.example.mypackage is a package hierarchy where mypackage is
a sub-package of example, and example is a sub-package of com.
Package Declaration:
In Java, packages are declared using the package keyword at the top of each source code file.
For example, package com.example.mypackage; declares that the class belongs to the
com.example.mypackage package.
Import Statement:
To use a class or interface from another package, you need to import it using the import
statement. For example, import com.example.mypackage.MyClass; allows you to use MyClass
from the com.example.mypackage package.
Java Standard Libraries:
Java uses packages extensively in its standard libraries. For instance, classes related to I/O
operations are in the java.io package, and classes for handling exceptions are in the java.lang
package.
Third-Party Libraries:
When you use third-party libraries in your Java applications, they are often packaged into JAR
files with well-organized package structures. This allows you to easily integrate and use these
libraries in your code.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 45


RV Institute of Technology and Management®

Code Reusability and Maintainability:


Packages encourage code reusability and maintainability. They help in keeping related classes
together, making it easier to locate, maintain, and extend code.
Documentation and Javadoc:
Packages play a crucial role in generating documentation using tools like Javadoc. By
organizing classes into packages, you can generate structured and meaningful documentation
for your code.
Best Practices:
It's a good practice to choose meaningful and unique package names, typically based on your
organization's domain name in reverse (e.g., com.example.mypackage).
Use consistent package naming conventions to make your code more readable and
maintainable.
Packages are a fundamental concept in programming that allows for organizing, managing, and
structuring code. They are essential for avoiding naming conflicts, promoting code
organization, and enhancing the reusability and maintainability of software. Packages are used
extensively in Java and many other programming languages to create well-structured and
modular applications.

Code:
package mypack;

public class Calculator {


public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}

public static int multiply(int a, int b) {


return a * b;
}

public static int divide(int a, int b) {


if (b != 0) {

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 46


RV Institute of Technology and Management®

return a / b;
} else {
throw new ArithmeticException("Division by zero is not allowed.");
}
}
}

import mypack.Calculator;

public class CalculatorApp {


public static void main(String[] args) {
int num1 = 10;
int num2 = 5;

int sum = Calculator.add(num1, num2);


int difference = Calculator.subtract(num1, num2);
int product = Calculator.multiply(num1, num2);
int quotient = Calculator.divide(num1, num2);

System.out.println("Sum: " + sum);


System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 47


RV Institute of Technology and Management®

Output:

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).
Threads are a fundamental concept in computer science and programming, allowing a program
to execute multiple tasks concurrently. Here are the key concepts related to threads:
Thread:
A thread is the smallest unit of a program's execution. It represents a single sequence of
instructions and operates independently within a process.
Threads are also known as lightweight processes because they share the same memory space
and resources of the parent process.
Multithreading:
Multithreading is a programming technique that allows a single process to have multiple
threads running concurrently.
Each thread within a process can execute different parts of the program, enabling parallelism
and potentially improving performance.
Concurrency vs. Parallelism:
Concurrency is the ability of a system to handle multiple tasks in overlapping time periods. It
doesn't necessarily mean that tasks are executed simultaneously.
Parallelism, on the other hand, involves tasks running at the same time on multiple processors
or cores, achieving true simultaneous execution.
Thread Creation:
Threads can be created in various ways, such as by extending the Thread class or implementing
the Runnable interface in Java.
Creating threads allows you to perform tasks concurrently and efficiently.
Thread States:
Threads can be in different states, including:
New: The thread has been created but not started yet.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 48


RV Institute of Technology and Management®

Runnable: The thread is ready to run, but the CPU scheduler has not selected it.
Running: The thread is currently executing its code.
Blocked: The thread is waiting for a resource or condition to become available.
Terminated: The thread has finished its execution.

Synchronization:
When multiple threads access shared resources concurrently, synchronization is used to prevent
data corruption or race conditions.
Locks, semaphores, and monitors are used to control thread access to critical sections of code.
Thread Safety:
Ensuring thread safety is crucial to prevent issues like data corruption or race conditions.
It involves designing code and data structures to work correctly and efficiently in a
multithreaded environment.
Communication Between Threads:
Threads often need to communicate and coordinate their actions. Various mechanisms, such as
message passing, shared memory, and thread signaling, can be used for this purpose.
Benefits of Multithreading:
Improved program responsiveness: Multithreading allows a program to remain responsive even
when performing time-consuming tasks.
Efficient resource utilization: Multithreading can make better use of multiple CPU cores and
resources.
Simplified program structure: Multithreading can make it easier to break complex tasks into
smaller, more manageable parts.
Challenges and Pitfalls:
Multithreading can introduce complexities like race conditions, deadlocks, and increased
debugging difficulties.
Careful design and thorough testing are required to avoid these pitfalls.
Thread Priority:
Threads can have different priorities that affect how the operating system schedules them for
execution. Higher-priority threads are favored but are not guaranteed exclusive execution.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 49


RV Institute of Technology and Management®

Thread Termination:
Properly terminating threads is important to avoid resource leaks. Threads can be terminated
gracefully or forcefully.
Threads are a powerful tool for enabling concurrent execution in modern software. They allow
programs to take advantage of multicore processors and improve performance and
responsiveness. However, multithreading also introduces complexities that need to be carefully
managed to ensure correct and efficient program behavior.

Code:
class MyRunnable implements Runnable {
public void run() {
try {
System.out.println("Thread started: " + Thread.currentThread().getName());
Thread.sleep(500); // Suspend the thread for 500 milliseconds
System.out.println("Thread ended: " + Thread.currentThread().getName());
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + Thread.currentThread().getName());
}
}
}

public class RunnableThreadExample {


public static void main(String[] args) {
System.out.println("Main thread started: " + Thread.currentThread().getName());

// Create multiple threads using the MyRunnable class


Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 50


RV Institute of Technology and Management®

// Start the threads


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

// Wait for the threads to finish


try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}

System.out.println("Main thread ended: " + Thread.currentThread().getName());


}
}

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 51


RV Institute of Technology and Management®

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

Code:
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Call the Thread class constructor with a thread name
start(); // Start the thread
}

public void run() {


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

public class ThreadExample {


public static void main(String[] args) {
System.out.println("Main thread started: " + Thread.currentThread().getName());

MyThread thread1 = new MyThread("Child Thread 1");


MyThread thread2 = new MyThread("Child Thread 2");

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 52


RV Institute of Technology and Management®

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


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

System.out.println("Main thread ended: " + Thread.currentThread().getName());


}
}

Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 53


RV Institute of Technology and Management®

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 54


RV Institute of Technology and Management®

13) Create a multi-threaded banking system where multiple customers can deposit and
withdraw money from their accounts concurrently while maintaining data
consistency.
Code:
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}

public synchronized void deposit(double amount) {


balance += amount;
}

public synchronized void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient funds for withdrawal.");
}
}

public synchronized double getBalance() {


return balance;
}
}

class CustomerThread extends Thread {


private BankAccount account;

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 55


RV Institute of Technology and Management®

public CustomerThread(BankAccount account) {


this.account = account;
}
public void run() {
for (int i = 0; i < 5; i++) {
double amount = Math.random() * 100;
account.deposit(amount);
System.out.println("Deposited: " + amount);

amount = Math.random() * 100;


account.withdraw(amount);
System.out.println("Withdrawn: " + amount);

System.out.println("Balance: " + account.getBalance());


}
}
}

public class BankingSystem {


public static void main(String[] args) {
BankAccount account = new BankAccount(1000.0);

CustomerThread customer1 = new CustomerThread(account);


CustomerThread customer2 = new CustomerThread(account);

customer1.start();
customer2.start();
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 56


RV Institute of Technology and Management®

}
Output:

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 57


RV Institute of Technology and Management®

15) Create a custom exception class called "ProductAddException" that extends the
standard Java "Exception" class.

Write a program that allows users to add products to the inventory. Implement exception
handling to catch and handle the following scenarios:

If the user tries to add a product with a negative price, throw a "ProductAddException"
with an appropriate error message.

If the user tries to add a product with a quantity less than 0, throw a
"ProductAddException" with a suitable error message.

Ensure that the program gracefully handles any other exceptions that may occur during
the product addition process
Code:
import java.util.Scanner;

class ProductAddException extends Exception {


public ProductAddException(String message) {
super(message);
}
}

class Product {
private String name;
private double price;
private int quantity;

public Product(String name, double price, int quantity) {


this.name = name;
this.price = price;
this.quantity = quantity;
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 58


RV Institute of Technology and Management®

@Override
public String toString() {
return "Product: " + name + " | Price: $" + price + " | Quantity: " + quantity;
}
}

public class InventoryManagement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.println("Add a new product to the inventory:");
System.out.print("Product Name: ");
String name = scanner.nextLine();

System.out.print("Product Price: $");


double price = scanner.nextDouble();

if (price < 0) {
throw new ProductAddException("Price cannot be negative.");
}

System.out.print("Product Quantity: ");


int quantity = scanner.nextInt();

if (quantity < 0) {
throw new ProductAddException("Quantity cannot be negative.");
}

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 59


RV Institute of Technology and Management®

Product product = new Product(name, price, quantity);

System.out.println("Product added to inventory:");


System.out.println(product);
} catch (ProductAddException e) {
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}
Output

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 60


RV Institute of Technology and Management®

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 61


RV Institute of Technology and Management®

Tentative questions for Viva Voce


What is OOPS?
OOPS is abbreviated as Object Oriented Programming system in which programs are
considered as a collection of objects. Each object is nothing but an instance of a class.

Write basic concepts of OOPS?


Following are the concepts of OOPS:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

What is a class?
A class is simply a representation of a type of object. It is the blueprint/plan/template that
describes the details of an object.

What is an Object?
An object is an instance of a class. It has its own state, behavior, and identity.

What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That
hidden data can be restricted to the members of that class.

Levels are Public, Protected, Private, Internal, and Protected Internal.

What is Polymorphism?
Polymorphism is nothing but assigning behavior or value in a subclass to something that was
already declared in the main class. Simply, polymorphism takes more than one form.

What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another
class. If Inheritance applied to one class is called Single Inheritance, and if it depends on
multiple classes, then it is called multiple Inheritance.

What are manipulators?


Manipulators are the functions which can be used in conjunction with the insertion ()
operators on an object. Examples are endl and setw.

Explain the term constructor


A constructor is a method used to initialize the state of an object, and it gets invoked at the
time of object creation. Rules for constructor are:

Constructor Name should be the same as a class name. A constructor must have no return
type.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 62


RV Institute of Technology and Management®

Define Destructor?
A destructor is a method which is automatically called when the object is made of scope or
destroyed. Destructor name is also same as class name but with the tilde symbol before the
name.

What is an Inline function?


An inline function is a technique used by the compilers and instructs to insert complete body
of the function wherever that function is used in the program source code.

What is a virtual function?


A virtual function is a member function of a class, and its functionality can be overridden in
its derived class. This function can be implemented by using a keyword called virtual, and it
can be given during function declaration.

A virtual function can be declared using a token(virtual) in C++. It can be achieved in


C/Python Language by using function pointers or pointers to function.

What is a friend function?


A friend function is a friend of a class that is allowed to access to Public, private, or protected
data in that same class. If the function is defined outside the class cannot access such
information.

A friend can be declared anywhere in the class declaration, and it cannot be affected by
access control keywords like private, public, or protected.

What is function overloading?


Function overloading is a regular function, but it can perform different tasks. It allows the
creation of several methods with the same name which differ from each other by the type of
input and output of the function.

Example
[crayon-5f2cf66ff2e66074243655/]
15) What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the
arguments. Operator,-,* can be used to pass through the function, and it has its own
precedence to execute

What is an abstract class?


An abstract class is a class which cannot be instantiated. Creation of an object is not possible
with an abstract class, but it can be inherited. An abstract class can contain only an Abstract
method. Java allows only abstract method in abstract class while other languages allow non-
abstract method as well.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 63


RV Institute of Technology and Management®

What is a ternary operator?


The ternary operator is said to be an operator which takes three arguments. Arguments and
results are of different data types, and it depends on the function. The ternary operator is also
called a conditional operator.

What is the use of finalize method?


Finalize method helps to perform cleanup operations on the resources which are not currently
used. Finalize method is protected, and it is accessible only through this class or by a derived
class.

What are the different types of arguments?


A parameter is a variable used during the declaration of the function or subroutine, and
arguments are passed to the function body, and it should match with the parameter defined.

There are two types of Arguments.

Call by Value – Value passed will get modified only inside the function, and it returns the
same value whatever it is passed into the function.
Call by Reference – Value passed will get modified in both inside and outside the functions
and it returns the same or different value.

What is the super keyword?


The super keyword is used to invoke the overridden method, which overrides one of its
superclass methods. This keyword allows to access overridden methods and also to access
hidden members of the superclass.

It also forwards a call from a constructor, to a constructor in the superclass.

What is method overriding?


Method overriding is a feature that allows a subclass to provide the implementation of a
method that overrides in the main class. It will override the implementation in the superclass
by providing the same method name, same parameter, and same return type.

What is an interface?
An interface is a collection of an abstract method. If the class implements an interface, it
thereby inherits all the abstract methods of an interface.

Java uses Interface to implement multiple inheritances.

What is exception handling?


An exception is an event that occurs during the execution of a program. Exceptions can be of
any type – Runtime exception, Error exceptions. Those exceptions are adequately handled
through exception handling mechanism like try, catch, and throw keywords.

What are tokens?

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 64


RV Institute of Technology and Management®

A compiler recognizes a token, and it cannot be broken down into component elements.
Keywords, identifiers, constants, string literals, and operators are examples of tokens.

Even punctuation characters are also considered as tokens. Example: Brackets, Commas,
Braces, and Parentheses.

What is the main difference between overloading and overriding?


Overloading is static Binding, whereas Overriding is dynamic Binding. Overloading is
nothing but the same method with different arguments, and it may or may not return the equal
value in the same class itself.

Overriding is the same method names with the same arguments and return types associated
with the class and its child class.

What is the main difference between a class and an object?

An object is an instance of a class. Objects hold multiple information, but classes don’t have
any information. Definition of properties and functions can be done in class and can be used
by the object.

A class can have sub-classes, while an object doesn’t have sub-objects.

What is an abstraction?
Abstraction is a useful feature of OOPS, and it shows only the necessary details to the client
of an object. Meaning, it shows only required details for an object, not the inner constructors,
of an object. Example – When you want to switch on the television, it is not necessary to
know the inner circuitry/mechanism needed to switch on the TV. Whatever is required to
switch on TV will be shown by using an abstract class.

What are the access modifiers?


Access modifiers determine the scope of the method or variables that can be accessed from
other various objects or classes. There are five types of access modifiers, and they are as
follows:

Private Protected Public Friend


Protected Friend

What are sealed modifiers?


Sealed modifiers are the access modifiers where the methods can not inherit it. Sealed
modifiers can also be applied to properties, events, and methods. This modifier cannot be
used to static members.

How can we call the base method without creating an instance?

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 65


RV Institute of Technology and Management®

Yes, it is possible to call the base method without creating an instance. And that method
should be “Static method."

Doing Inheritance from that class.-Use Base Keyword from a derived class.

What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base
class function. Whereas, Override modifier helps to override the base class function.

What are the various types of constructors?

There are three types of constructors:

–Default Constructor – With no parameters.

–Parametric Constructor – With Parameters. Create a new instance of a class and also passing
arguments simultaneously.

–Copy Constructor – Which creates a new object as a copy of an existing object.

What is early and late Binding?


Early binding refers to the assignment of values to variables during design time, whereas late
Binding refers to the assignment of values to variables during run time.

What is 'this' pointer?


THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which
differentiates between the current object with the global object. It refers to the current object.

What is the difference between structure and a class?


The default access type of a Structure is public, but class access type is private. A structure is
used for grouping data, whereas a class can be used for grouping data and methods.
Structures are exclusively used for data, and it doesn't require strict validation, but classes are
used to encapsulate and inherent data, which requires strict validation.

What is the default access modifier in a class?


The default access modifier of a class is Private by default.

What is a pure virtual function?


A pure virtual function is a function which can be overridden in the derived class but cannot
be defined. A virtual function can be declared as Pure by using the operator =0.

Example -
[crayon-5f2cf66ff2e6f715458999/]
38) What are all the operators that cannot be overloaded?

Following are the operators that cannot be overloaded -.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 66


RV Institute of Technology and Management®

1. Scope Resolution (::)


2. Member Selection (.)
3. Member selection through a pointer to function (.*)

What is dynamic or run time polymorphism?

Dynamic or Run time polymorphism is also known as method overriding in which call to an
overridden function is resolved during run time, not at the compile time. It means having two
or more methods with the same name, same signature but with different implementation.

Do we require a parameter for constructors?

No, we do not require a parameter for constructors.

What is a copy constructor?

This is a special constructor for creating a new object as a copy of an existing object. There
will always be only one copy constructor that can be either defined by the user or the system.

What does the keyword virtual represented in the method definition?


It means we can override the method.

Whether static method can use nonstatic members?


False.

What are a base class, subclass, and superclass?

The base class is the most generalized class, and it is said to be a root class. A Subclass is a
class that inherits from one or more base classes.
The superclass is the parent class from which another class inherits.

What is static and dynamic Binding?


Binding is nothing but the association of a name with the class. Static Binding is a binding in
which name can be associated with the class during compilation time, and it is also called as
early Binding.

Dynamic Binding is a binding in which name can be associated with the class during
execution time, and it is also called as Late Binding.

How many instances can be created for an abstract class?


Zero instances will be created for an abstract class. In other words, you cannot create an
instance of an Abstract Class.

Which keyword can be used for overloading?


Operator keyword is used for overloading.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 67


RV Institute of Technology and Management®

What is the default access specifier in a class definition?


Private access specifier is used in a class definition.

Which OOPS concept is used as a reuse mechanism?


Inheritance is the OOPS concept that can be used as a reuse mechanism.

Which OOPS concept exposes only the necessary information to the calling functions?
Encapsulation

What is the difference between an Inner Class and a Sub-Class?


An Inner class is a class which is nested within another class. An Inner class has access rights
for the class which is nesting it and it can access all variables and methods defined in the
outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can
access all public and protected methods and fields of its super class.

What are the various access specifiers for Java classes?


In Java, access specifiers are the keywords used before a class name which defines the access
scope. The types of access specifiers for classes are:

1. Public : Class,Method,Field is accessible from anywhere.

2. Protected:Method,Field can be accessed from the same class to which they belong or
from the sub-classes,and from the class of same package,but not from outside.

3. Default: Method,Field,class can be accessed only from the same package and not
from outside of it’s native package.

4. Private: Method,Field can be accessed from the same class to which they belong.

What's the purpose of Static methods and static variables?


When there is a requirement to share a method or a variable between multiple objects of a
class instead of creating separate copies for each object, we use static keyword to make a
method or variable shared for all objects.

What is data encapsulation and what's its significance?


Encapsulation is a concept in Object Oriented Programming for combining properties and
methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software development as


each object has its own set of methods and variables and serves its functions independent of
other objects. Encapsulation also serves data hiding purpose.

What is a singleton class? Give a practical example of its usage.


A singleton class in java can have only one instance and hence all its methods and variables
belong to just one instance. Singleton class concept is useful for the situations when there is a

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 68


RV Institute of Technology and Management®

need to limit the number of objects for a class.

The best example of singleton usage scenario is when there is a limit of having only one
connection to a database due to some driver limitations or because of any licensing issues.

What are Loops in Java? What are three types of loops?


Looping is used in programming to execute a statement or a block of statement repeatedly.
There are three types of loops in Java:

1) For Loops

For loops are used in java to execute statements repeatedly for a given number of times. For
loops are used when number of times to execute the statements is known to programmer.

2) While Loops

While loop is used when certain statements need to be executed repeatedly until a condition
is fulfilled. In while loops, condition is checked first before execution of statements.

3) Do While Loops

Do While Loop is same as While loop with only difference that condition is checked after
execution of block of statements. Hence in case of do while loop, statements are executed at
least once.

What is an infinite Loop? How infinite loop is declared?

An infinite loop runs without any condition and runs infinitely. An infinite loop can be
broken by defining any breaking logic in the body of the statement blocks.

Infinite loop is declared as follows:

for (;;)

// Statements to execute

// Add any loop breaking logic

What is the difference between continue and break statement?


break and continue are two important keywords used in Loops. When a break keyword is

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 69


RV Institute of Technology and Management®

used in a loop, loop is broken instantly while when continue keyword is used, current
iteration is broken and loop continues with next iteration.

In below example, Loop is broken when counter reaches 4. for


(counter=0;counter<10;counter++)

system.out.println(counter); if (counter==4) {
break;}

In the below example when counter reaches 4, loop jumps to next iteration and any
statements after the continue keyword are skipped for current iteration.

for (counter=0;counter<10;counter++) system.out.println(counter);

if (counter==4) { continue;
}

system.out.println("This will not get printed when counter is 4");

What is the difference between double and float variables in Java?


In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single
precision floating point decimal number while Double is double precision decimal number.

What is Final Keyword in Java? Give an example.


In java, a constant is declared using the keyword Final. Value can be assigned only once and
after assignment, value of a constant can’t be changed.

In below example, a constant with the name const_val is declared and assigned avalue:
Private Final int const_val=100
When a method is declared as final,it can NOT be overridden by the subclasses.This method
are faster than any other method,because they are resolved at complied time.

When a class is declares as final,it cannot be subclassed. Example String,Integer and other
wrapper classes.

What is ternary operator? Give an example.


Ternary operator , also called conditional operator is used to decide which value to assign to

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 70


RV Institute of Technology and Management®

a variable based on a Boolean value evaluation. It's denoted as ?


In the below example, if rank is 1, status is assigned a value of "Done" else "Pending". public
class conditionTest {
public static void main(String args[]) {
String status; int rank = 3;
status = (rank == 1) ? "Done" : "Pending"; System.out.println(status);
}
}

In multi-threading how can we ensure that a resource isn't used by multiple threads
simultaneously?
In multi-threading, access to the resources which are shared among multiple threads can be
controlled by using the concept of synchronization. Using synchronized keyword, we can
ensure that only one thread can use shared resource at a time and others can get control of the
resource only once it has become free from the other one using it.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 71


RV Institute of Technology and Management®

List of mini projects:


1. Create a simple command-line calculator program that can perform basic arithmetic
operations.
2. Develop a program that calculates and displays the grade of a student based on their exam
scores.
3. Implement a to-do list application that allows users to add, remove, and view tasks.
4. Design a program for a library that manages books, allowing users to check out and return
books.
5. Build a user registration and login system with basic user authentication.
6. Create a currency conversion program that converts between different currencies using
exchange rates.
7. Design a program that simulates creating and managing user profiles for a social media
platform.
8. Implement a car rental system that allows users to rent and return vehicles, with basic
billing calculations.
9. Create a program for a university to enroll and manage students in different courses.
10. Design a program for a restaurant to take customer orders, calculate the bill, and manage
the kitchen's order queue.
11. Build a calendar application that allows users to schedule and manage events and
appointments.
12. Develop an expense tracker that allows users to log and categorize expenses, view
spending summaries, and set budgets.
13. Create a simple two-player Tic-Tac-Toe game.
14. Create a program that fetches and displays weather forecasts.
15. Design a simple address book application that allows users to store and manage contact
information?
16. Build a program for generating and managing invoices for a small business or freelance
work.
17. Build a program that simulates a simple online quiz with multiple-choice questions and
calculates the user's score.
18. Design a program that simulates a basic stock trading platform where users can buy and
sell shares.
19. Implement a program that generates and manages a basic employee payroll system,
calculating salaries and taxes.
20. Create a program that generates random art patterns or fractals, offering a visually creative
experience.

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB (BCS306A) 72

You might also like