Ooc With Java Lab Manual BCS306A Explanation
Ooc With Java Lab Manual BCS306A Explanation
Ooc With Java Lab Manual BCS306A Explanation
LABORATORY MANUAL
SEMESTER: III
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
CourseDetails
Year/Semester 2nd Academic Year 2022-23
Course Title Object Oriented Programming With JAVA Course Code BCS306A
Course Type CIE Marks 50
(Theory/Practical SEE Marks 50
Theory
/Integrated) Total Marks 100
Teaching
3:0:2:0 Duration of SEE 3
Hours/Week(L:T:P:S)
Lab Manual Authors Sign- Date
Institute Mission:
To Enrich Students with the essence of science and engineering knowledge, Professional ethics
and social values.
To instill creativity and Research Temperament to Reach the Greater Heights of Professional
Success.
Program Objectives: The educational objectives of the Mechanical Engineering Program are to
prepare our graduates to:
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
PO2:Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural science, and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, cultural, societal and environmental considerations.
PO4: Conduct investigations of complex problems: Use of research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
1
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
PO7:Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of and need
for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams and in multidisciplinary settings.
PO12: 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.
Course Objectives
Course Outcomes
At the end of the course, the student will be able to:
CO1 Demonstrate proficiency in writing simple programs involving branching and looping structures.
CO2 Design a class involving data members and methods for the given scenario.
CO3 Apply the concepts of inheritance and interfaces in solving real world problems.
CO4 Use the concept of packages and exception handling in solving complex problem
CO5 Apply concepts of multithreading, auto boxing and enumerations in program development
Dep of CSE 2
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
Assessment Detail
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the SEE minimum
passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be deemed to have satisfied the
academic requirements and earned the credits allotted to each subject/ course if the student secures a minimum of
40% (40 marks out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End
Examination) taken together. CIE for the theory component of the IPCC (maximum marks 50)
● IPCC means practical portion integrated with the theory of the course.
● CIE marks for the theory component are 25 marks and that for the practical component is 25 marks.
● 25 marks for the theory component are split into 15 marks for two Internal Assessment Tests (Two Tests,
each of 15 Marks with 01-hour duration, are to be conducted) and 10 marks for other assessment methods
mentioned in 22OB4.2. The first test at the end of 40-50% coverage of the syllabus and the second test after
covering 85-90% of the syllabus.
● Scaled-down marks of the sum of two tests and other assessment methods will be CIE marks for the theory
component of IPCC (that is for 25 marks).
● The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC. 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 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.
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)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum
of 3 sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
4. Marks scored by the student shall be proportionally scaled down to 50 Marks The theory portion of the
IPCC shall be for both CIE and SEE, whereas the practical portion will have a CIE component only.
Questions mentioned in the SEE paper may include questions from the practical component. Suggested
Learning Resources: Textbook 15.09.2023 14.09.2023 Annexure-II 5
Dep of CSE 3
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
5 1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021, McGraw-Hill,
ISBN: 9781260463422
Reference Books 1. Programming with Java, 6th Edition, by E Balagurusamy, Mar-2019, McGraw Hill
Education, ISBN: 9789353162337.
● Introduction To Programming In Java (by Evan Jones, Adam Marcus and Eugene Wu):
https://ocw.mit.edu/courses/6-092-introduction-to-programming-in-java-january-iap-2010/
Dep of CSE 4
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
2 Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack operations.
A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raise Salary (percent)
3
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.
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.
4 ● 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.
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
5
(). Demonstrate polymorphism concepts by developing suitable methods, defining member
data and main program.
Develop a JAVA program to create an abstract class Shape with abstract methods
calculate Area() and calculate Perimeter(). Create subclasses Circle and Triangle that
6
extend the Shape class and implement the respective methods to calculate the area and
perimeter of each shape.
Dep of CSE 5
OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]
Develop a JAVA program to create an interface Resizable with methods resize Width (int
7 width) and resize Height(int height) that allow an object to be resized. Create a class
Rectangle that implements the Resizable interface and implements the resize methods
Develop a JAVA program to create an outer class with a function display. Create another
8 class inside the outer class named inner with a function called display and call the two
functions in the main class.
Develop a JAVA program to raise a custom exception (user defined exception) for
9
Division By Zero using try, catch, throw and finally.
Develop a JAVA program to create a package named mypack and import & implement it
10
in a suitable class.
Write a program to illustrate creation of threads using runnable class. (start method start
11 each of the newly created thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).
Develop a program to create a class My Thread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts after
12
this. It can be observed that both main thread and created child thread are executed
concurrently.
Dep of CSE 6
OBJECT ORIENTED PROGRAMMING WITH JAVA
import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the order N of the matrices: ");
int N = scanner.nextInt();
int[][] matrix1 = new int[N][N];
int[][] matrix2 = new int[N][N];
int[][] sumMatrix = new int[N][N];
// Adding matrices
sumMatrix = addMatrices(matrix1, matrix2);
scanner.close();
}
// Method to input elements of a matrix
private static void inputMatrix(int[][] matrix, Scanner scanner) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print("Enter element at position (" + i + ", " + j + "): ");
matrix[i][j] = scanner.nextInt();
}
}
}
javac MatrixAddition.java
java MatrixAddition
Matrix1:
12
34
Matrix2:
56
78
Sum of the matrices:
68
10
Or
import java.util.Scanner;
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
public class Stack
{
private static final int MAX_SIZE = 10;
private int[] array;
private int top;
public Stack() {
array = new int[MAX_SIZE];
top = -1;
}
} else {
int poppedValue = array[top--];
System.out.println("Popped: " + poppedValue);
}
}
O/P:
Pushed: 5
Pushed: 10
Pushed: 15
Stack: 5 10 15
Popped: 15
Stack: 5 10
Popped: 10
Popped: 5
Stack:
Operations
The two main operations on a stack are push, which adds an item,
and pop, which removes the most recently added item.
Analogy
The name "stack" comes from the physical act of stacking items on top
of each other, like a stack of plates.
Implementation
A stack can be implemented as a singly linked list, with a pointer to the
top element.
Recursive functions:
When a function is called recursively on a computer, the stack is
used to keep track of each individual function call made by the
computer. As a function is finished being executed, its contents
are “popped” off the stack, and each new call is “pushed” onto
the stack.
3. A class called Employee, which models an employee with an ID, name and salary. The method
raiseSalary (percent) increases the salary by the given percentage. Develop the Employee class
and suitable main method for demonstration.
// Constructor
public Employee(int empId, String name, double salary) {
this.empId = empId;
this.name = name;
this.salary = salary;
}
Output:
Before raise:
Employee ID: 1
Name: John Henry
Salary: 50000.0
After raise:
Employee ID: 1
Name: John Henry
Salary: 55000.0
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.
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
O/P:
Point1 coordinates after setXY: 1, 2
Point2 coordinates: (3, 4)
Distance from Point1 to Point2: 2.8284271247461903
Distance from Point2 to Origin: 5.0
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.
class Shape {
protected String name;
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
@Override
public void erase() {
System.out.println("Erasing a circle with radius " + radius);
}
}
@Override
public void draw() {
System.out.println("Drawing a triangle with base " + base + " and height " + height);
}
@Override
public void erase() {
System.out.println("Erasing a triangle with base " + base + " and height " + height);
}
}
@Override
public void draw() {
System.out.println("Drawing a square with side length " + side);
}
@Override
public void erase() {
System.out.println("Erasing a square with side length " + side);
}
}
O/P:
$ java ShapeDemo
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0
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.
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
double calculatePerimeter() {
O/P:
$ java ShapeDemo
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
// Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
@Override
public void resizeHeight(int height) {
this.height = height;
System.out.println("Resized height to: " + height);
}
O/P:
$ java ResizeDemo
Original Rectangle Info:
Rectangle: Width = 10, Height = 5
Resized width to: 15
Resized height to: 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.
class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
O/P:
$ java OuterInnerDemo
Outer class display method
Inner class display method
9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
try
{
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e)
{
System.out.println("Exception caught: " + e.getMessage());
}
finally
{
System.out.println("Finally block executed");
}
}
}
O/P:
$ java CustomExceptionDemo
10. Develop a JAVA program to create a package named mypack and import & implement it in
a suitable class.
}
}
To compile and run this program, you need to follow these steps:
Organize your directory structure as follows:
project-directory/
├── mypack/
│ └── MyPackageClass.java
└── PackageDemo.java
Compile the files:
javac mypack/MyPackageClass.java
javac PackageDemo.java
O/P:
$ java PackageDemo
Hello from MyPackageClass in mypack package!
Result of adding numbers: 8
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 500milliseconds).
@Override
@SuppressWarnings("deprecation")
public void run() {
while (running) {
try {
// Suppress deprecation warning for Thread.sleep()
Thread.sleep(500);
System.out.println("Thread ID: " + Thread.currentThread().getId() + " is running.");
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
O/P:
$ java RunnableThreadExample
Thread ID: 24 is running.
Thread ID: 21 is running.
Thread ID: 20 is running.
Thread ID: 23 is running.
Thread ID: 22 is running.
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.
// The run method that will be executed when the thread starts
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " Count: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " Thread interrupted.");
}
}
}
}
// Main thread
for (int i = 1; i <= 5; i++) {
O/P:
$ java ThreadConcurrentExample
main Thread Count: 1
Child Thread Count: 1
main Thread Count: 2
Child Thread Count: 2
main Thread Count: 3
Child Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5