OOP With JAVA - BCS306A Lab Manual
OOP With JAVA - BCS306A Lab Manual
LAB MANUAL
OOPS WITH JAVA PROGRAMMING LABORATORY
(BCS306A)
Semester III
SEMESTER – III
Course Code BCS306A CIE Marks 50
Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE Marks 50
Course Objectives
Prog P P P P
P P P P P P P P P P P P
rams S S S S
Course Outcomes O O O O O O O O O O O O
cover O O O O
1 2 3 4 5 6 7 8 9 10 11 12
ed 1 2 3 4
Demonstrate proficiency 2 3 3 2 3 - - - 2 - - 2 2 - 2 2
in writing simple
programs involving 1-12
branching and looping
CO1 structures.
CORRELATION
PROGRAM OUTCOMES (PO), PROGRAM SPECIFIC OUTCOMES (PSO)
LEVELS
Moderate/
PO3 Design/development of solutions PO9 Individual and teamwork 2
Medium
PSO1 Design and develop applications using different stacks of web and programming technologies.
PSO2 Design and develop secure, parallel, distributed, networked, and digital systems.
PSO3 Apply software engineering methods to design, develop, test and manage software systems.
PSO4 Design and develop intelligent applications for business and industry.
Syllabus
1. Develop a JAVA program to add TWO matrices of suitable order N (The value of N should
be read from command line arguments).
2. Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
3. A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raiseSalary (percent) increases
the salary by the given percentage. Develop the Employee class and suitable main method for
demonstration.
4. A class called MyPoint, which models a 2D point with x and y coordinates, is designed as
follows:
11. Write a program to illustrate creation of threads using a runnable class. (start method
start each of the newly created thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).
12. Develop a program to create a class MyThread in this class a constructor, call the base
class constructor, using super and start the thread. The run method of the class starts after
this. It can be observed that both main thread and created child thread are executed
concurrently.
Introduction
Editor will show red line under the word if any compilation error is there.
To execute the program click on run button or right click on the code and choose run
configuration.
You can see the output on console present below the editor.
************************************************************************************
Program 1:
Develop a JAVA program to add TWO matrices of suitable order N (The value of N should be
read from command line arguments).
******************************************************************************
Algorithm for Matrix Addition Program:
Step-1: Start
Step-2: Print "Enter the number to create n*n matrix: "
Step-3: Read an integer num from the user (or from command-line arguments).
Step-4: Declare three 2D integer arrays: matrix1, matrix2, and Result, each of size num x num.
Step-5: Print "Enter values for matrix 1:"
Step-6: Loop for i from 0 to num - 1:
Department of Computer Science & Engineering, CMRIT, Bangalore
Java Programming Laboratory – BCS306A Academic Year: 2023-24
}
******************************************************************************
Output:
******************************************************************************
Program 2:
Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
******************************************************************************
Algorithm for Stack Operations:
1.Start
2.Initialize an array array of integers with a maximum size of 10.
3. Initialize top to -1 to indicate an empty stack.
4. Create a constructor Program2_Stack:
Initialize array with a size of 10.
Set top to -1.
5. Define a method push(int value):
Check if top is less than MAX_SIZE - 1 (stack is not full):
Increment top by 1.
Set array[top] to value.
public Program2_Stack() {
array = new int[MAX_SIZE];
top = -1; // Initialize top as -1 to indicate an empty stack
}
if (top >= 0) {
System.out.println("Stack elements: ");
for (int i = top; i >= 0; i--) {
System.out.println(array[i]);
}
System.out.println();
} else {
System.out.println("Stack is empty.");
}
}
while(true){
System.out.println("Press 1. for push 2 for pop 3. for display 4 for exit: ");
int ch = sc.nextInt();
switch(ch) {
case 1: System.out.println("How many values you want to push : ");
int n = sc.nextInt();
for(int i = 0; i<n; i++)
{
System.out.println("Enter " + (i+1) + "value: ");
stack.push(sc.nextInt());
}
break;
case 2: stack.pop();
break;
case 3: stack.display();
break;
case 4: System.exit(0);
}
}
}
******************************************************************************
Output:
Press 1. for push 2 for pop 3. for display 4 for exit:
1
How many values you want to push :
Department of Computer Science & Engineering, CMRIT, Bangalore
Java Programming Laboratory – BCS306A Academic Year: 2023-24
3
Enter 1value:
10
Pushed: 10
Enter 2value:
20
Pushed: 20
Enter 3value:
30
Pushed: 30
Press 1. for push 2 for pop 3. for display 4 for exit:
3
Stack elements:
30
20
10
salary by the given percentage. Develop the Employee class and suitable main method for
demonstration.
***************************************************************************
Algorithm
1.Start
2. Create a class Employee with private fields for ID, name, and salary, along with methods for
initialization, raising salary, and displaying employee information.
3.In the main method:
Initialize a Scanner object for user input.
Prompt the user for the number of employees (n).
Create an array of Employee objects with a size of n.
4. Use a loop to input details for each employee:
Inside the loop, prompt the user for employee ID, name, and salary.
Create an Employee object with the entered details and store it in the array.
5. Display the initial employee information:
Iterate through the array of employees.
For each employee, call the displayInfo method to show their details.
6. Prompt the user for a salary increment percentage.
7. Use a loop to raise the salary of each employee:
Inside the loop, call the raiseSalary method for each employee with the entered
increment percentage.
8. Display the updated employee information after the salary increment:
Iterate through the array of employees.
For each employee, call the displayInfo method to show their updated details.
9. End
************************************************************************
Program Code:
import java.util.Scanner;
}
}
}
***************************************************************************
Output:
Enter how many employee details you want to enter:
2
Enter Employee 1 id:
101
Enter Employee 1 name:
rajni
Enter Employee 1 salary:
40000
Enter Employee 2 id:
102
Enter Employee 2 name:
rahul
Enter Employee 2 salary:
50000
Initial Employee Information:
Employee ID: 101
Employee Name: rajni
Algorithm:
MyPoint Class:
1. Create a class called MyPoint to model a 2D point with x and y coordinates.
2. Declare private instance variables x and y to store the coordinates.
3. Define a default constructor for MyPoint that initializes the point at the default location
(0, 0).
4. Define an overloaded constructor for MyPoint that accepts x and y coordinates as
parameters and sets the point to the specified location.
5. Implement a setXY method that allows setting both x and y coordinates.
6. Implement a getXY method that returns the x and y coordinates as a 2-element integer
array.
7. Override the toString method to provide a string description of the point in the format
"(x, y)".
8. Implement a distance method that calculates the distance from the current point to
another point specified by its x and y coordinates.
9. Implement an overloaded distance method that calculates the distance from the current
point to another MyPoint instance.
10. Implement another overloaded distance method that calculates the distance from the
current point to the origin (0, 0).
Program4:
1. Create a Java class called Program4 to test the methods of the MyPoint class.
In the main method of Program4:
2. Create instances of MyPoint (point1 and point2) with specified coordinates.
3. Display the coordinates of point1 and point2 using the toString method.
4. Calculate and display the distance from point1 to a specific point, from point1 to point2,
and from point1 to the origin.
5. Test the setXY and getXY methods by setting new coordinates for point1, getting the
coordinates, and displaying the updated point and coordinates.
6. End the program.
Program Code:
class MyPoint {
private int x;
private int y;
// Method to return a string description of the point in the format "(x, y)"
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
Point 1: (3, 4)
Point 2: (6, 8)
Distance from Point 1 to (6, 8): 5.0
Distance from Point 1 to Point 2: 5.0
Distance from Point 1 to the origin: 5.0
Point 1 after setXY(5, 10): (5, 10)
Coordinates of Point 1: (5, 10)
Program 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.
Algorithm:
1. Start the program.
2. Create a class named Shape with two methods:
draw(): Display the message "Drawing a shape."
erase(): Display the message "Erasing a shape."
3. Create a subclass Circle that extends Shape with two overridden methods:
}
}
// Circle class
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public void erase() {
System.out.println("Erasing a circle");
}
}
// Triangle class
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle");
}
@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}
// Square class
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
@Override
public void erase() {
System.out.println("Erasing a square");
}
}
shape1.draw();
shape1.erase();
shape2.draw();
shape2.erase();
shape3.draw();
shape3.erase();
}}
Output:
Drawing a circle
Erasing a circle
Drawing a triangle
Erasing a triangle
Drawing a square
Erasing a square
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.
Algorithm:
1.Start the program.
2.Display a message to "Enter radius:".
3. Create a Scanner object to read input from the user.
4. Read the value entered by the user as the radius (as a double) using sc.nextDouble() and
store it in a variable r.
5. Create an instance of the Circle1 class with the provided radius r.
6. Display a message to "Enter side 1:".
7. Read the value entered by the user as the first side length (as a double) using sc.nextDouble()
and store it in a variable a.
8. Display a message to "Enter side 2:".
Department of Computer Science & Engineering, CMRIT, Bangalore
Java Programming Laboratory – BCS306A Academic Year: 2023-24
9. Read the value entered by the user as the second side length (as a double) using
sc.nextDouble() and store it in a variable b.
10. Display a message to "Enter side 3:".
11. Read the value entered by the user as the third side length (as a double) using
sc.nextDouble() and store it in a variable c.
12. Create an instance of the Triangle1 class with the provided side lengths a, b, and c.
13.Calculate the area and perimeter of the circle using the calculateArea() and
calculatePerimeter() methods of the Circle1 object and store the results in variables.
14. Calculate the area and perimeter of the triangle using the calculateArea() and
calculatePerimeter() methods of the Triangle1 object and store the results in variables.
15. Display the calculated area and perimeter of the circle and triangle.
16. End the program.
***************************************************************************
Program Code:
import java.util.Scanner;
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
@Override
double calculateArea() {
@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
}
}
***************************************************************************
Output:
Enter radius:
2
Enter side 1 :
2
Enter side 2 :
3
Enter side 3 :
4
Circle Area: 12.566370614359172
Circle Perimeter: 12.566370614359172
Triangle Area: 2.9047375096555625
Triangle Perimeter: 9.0
***************************************************************************
Program 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.
*******************************************************************************
Algorithm:
1. Start the program.
2. Define an interface named Resizable with two abstract methods:
resizeWidth(int width): Takes an integer width and is responsible for resizing the
width of an object implementing the interface.
resizeHeight(int height): Takes an integer height and is responsible for resizing
the height of an object implementing the interface.
3. Create a class named Rectangle that implements the Resizable interface.
Initialize private instance variables width and height with the values passed to the
constructor.
Implement the resizeWidth(int rewidth) method:
If the provided rewidth is greater than 0, update the width of the rectangle to
rewidth.Otherwise, display the message "Width must be greater than 0."
Implement the resizeHeight(int reheight) method:
If the provided reheight is greater than 0, update the height of the rectangle to
reheight.Otherwise, display the message "Height must be greater than 0."
Define a displayDimensions() method to display the current width and height of the
rectangle.
4. In the main method:
Create a Rectangle object with an initial width of 10 and height of 5.
@Override
public void resizeWidth(int rewidth) {
if (width > 0) {
this.width = rewidth;
} else {
System.out.println("Width must be greater than 0.");
}
}
@Override
public void resizeHeight(int reheight) {
if (height > 0) {
this.height = reheight;
} else {
System.out.println("Height must be greater than 0.");
}
}
***********************************************************************
Program Code:
// Outer class
class Outer {
void display() {
System.out.println("This is the outer class's display method.");
}
// Inner class
class Inner {
void display() {
System.out.println("This is the inner class's display method.");
}
}
}
// Create an instance of the inner class using the outer class's instance
Algorithm:
1. Start the program.
2. Import the Scanner class for user input.
3. Define a custom exception class DivisionByZeroException that extends the Exception
class. This class is used for custom exceptions with a specific error message.
4. In the main method:
Create a Scanner object sc to read input from the user.
Inside a try block:
Display a message "Enter dividend: ".
Read an integer dividend from the user using sc.nextInt().
Display a message "Enter divisor: ".
Read an integer divisor from the user using sc.nextInt().
Check if divisor is zero:
If divisor is zero, throw a DivisionByZeroException with the message
"Division by zero is not allowed."
Calculate the result of division result as dividend / divisor.
Display the result of the division.
Catch the DivisionByZeroException if it is thrown and display the custom
exception message.
Catch the ArithmeticException (for division by zero) and display a
message for it.
In the finally block, display "Finally block executed."
5. End the program.
***********************************************************************
Program Code:
import java.util.Scanner;
if (divisor == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
Enter divident:
30
Enter divisor:
2
Result of division: 15
Finally block executed.
***************************************************************************
Program 10:
Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
**************************************************************************
Algorithm:
Step 1. Create a Package
1. Start the program.
2. Create a directory (folder) named "mypack" in your project directory.
3. Inside the "mypack" directory, you can place one or more Java source files that define classes,
interfaces, or other elements you want to include in the package.
Step 2: Define a Class in the Package 4. Create a Java source file inside the "mypack" directory with the
class you want to include in the package. For example:
File: mypack/MyClass.java
Package declaration: package mypack;
Define a class in the package, e.g., public class MyClass.
Step 3: Create a Class to Import the Package 5. Create another Java class in a different directory
(package) where you want to import and use the "mypack" package. For example:
File: MyMainClass.java
Import statement: import mypack.MyClass;
Define a class in this file, e.g., public class MyMainClass.
Step 4: Compile and Run 6. Compile both the "MyMainClass.java" and "mypack/MyClass.java" files
together. Ensure that the directory structure matches the package structure.
Compile commands: javac MyMainClass.java and javac mypack/MyClass.java.
Run the program using the java MyMainClass command.
Step 5:
Execution 8. The program executes, and you should see the output or behavior as specified in your code.
Step 6:End the program.
**************************************************************************
Program Code:
@Override
public void run() {
System.out.println("Thread " + threadName + " is starting.");
try {
// Sleep for 500 milliseconds (0.5 seconds)
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " was interrupted.");
}
System.out.println("Thread " + threadName + " is exiting.");
}
}
In the constructor of MyThread, call the constructor of the base class (Thread
class) using super("My Thread") to set the thread name and specify that it's a
child thread.
Display information about the child thread.
Start the child thread using the start() method.
3. In the run method of MyThread:
Simulate some work by counting down from 5 to 1.
Pause the thread for 1 second (1000 milliseconds) using Thread.sleep(1000).
Handle the InterruptedException if it occurs.
Display a message indicating that the child thread is exiting.
4. In the main method:
Create an instance of the MyThread class, which starts the child thread.
5. In the main method, the main thread:
Counts down from 5 to 1.
Pauses for 2 seconds (2000 milliseconds) between each count.
Handles the InterruptedException if it occurs.
Displays a message indicating that the main thread is exiting.
6. Both the main thread and the child thread run concurrently, and their output is
interleaved.
7. End the program.
**************************************************************************
Program Code:
class MyThread extends Thread {
MyThread() {
// Call the constructor of the base class (Thread class)
super("My Thread");
System.out.println("Child thread: " + this);
// Start the thread
start();
}
}
}
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted.");
}
System.out.println("Main Thread exiting.");
}
}
***************************************************************************Out
put:
Case 1:
Child thread: Thread[My Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Child Thread exiting.
Main Thread: 2
Main Thread: 1
Main Thread exiting.
********************************End***************************************
Problem name
Find the total number of characters, number of characters, and percentage of uppercase letters,
lowercase letters, digits, and special characters
Problem statement
Write a program to find the total number, number of characters and percentage of uppercase
letters, lowercase letters, digits and special characters in a given string without using length ()
function.
Input Format
Output Format
Integers (Total characters, count and percentage of upper case, lower case, digits & others)
Sample Input:
JAVA Programming@#$1234
Sample Output:
23 5 21 10 43 4 17 4 17
import java.util.Scanner;
public class one {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String data = scanner.nextLine();
char [] charArray = data.toCharArray();
int upper = 0;
int lower = 0;
int digit = 0;
int others = 0;
int l=0;
for(char c: charArray)
{
l++;
}
int totalChars = l;
for(int i=0; i<l; i++)
{
if (Character.isUpperCase(charArray[i]))
{
upper++;
}
else if(Character.isLowerCase(charArray[i]))
{
lower++;
}
else if(Character.isDigit(charArray[i]))
{
digit++;
}
else
{
others++;
}
}
System.out.print(totalChars);
System.out.print(" "+upper);
System.out.print(" "+(upper*100)/totalChars);
System.out.print(" "+lower);
System.out.print(" "+(lower*100)/totalChars);
System.out.print(" "+digit);
System.out.print(" "+(digit*100)/totalChars);
System.out.print(" "+others);
System.out.print(" "+(others*100)/totalChars);
}
}