0% found this document useful (0 votes)
42 views39 pages

OOP With JAVA - BCS306A Lab Manual

The document is a lab manual for the OOPS with Java Programming Laboratory (BCS306A) at CMR Institute of Technology for the academic year 2023-24. It outlines course objectives, prerequisites, outcomes, and a detailed syllabus including various programming tasks and algorithms related to Java programming concepts such as matrix addition, stack operations, inheritance, and multithreading. The document serves as a guide for students to develop their programming skills through practical exercises.

Uploaded by

doggoboy75
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)
42 views39 pages

OOP With JAVA - BCS306A Lab Manual

The document is a lab manual for the OOPS with Java Programming Laboratory (BCS306A) at CMR Institute of Technology for the academic year 2023-24. It outlines course objectives, prerequisites, outcomes, and a detailed syllabus including various programming tasks and algorithms related to Java programming concepts such as matrix addition, stack operations, inheritance, and multithreading. The document serves as a guide for students to develop their programming skills through practical exercises.

Uploaded by

doggoboy75
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
You are on page 1/ 39

Java Programming Laboratory – BCS306A Academic Year: 2023-24

CMR INSTITUTE OF TECHNOLOGY


Department of Computer Science and Engineering

LAB MANUAL
OOPS WITH JAVA PROGRAMMING LABORATORY
(BCS306A)

Semester III

Academic Year: 2023-24

OOPS WITH JAVA PROGRAMMING LABORATORY


Department of Computer Science & Engineering, CMRIT, Bangalore
Java Programming Laboratory – BCS306A Academic Year: 2023-24

SEMESTER – III
Course Code BCS306A CIE Marks 50
Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE Marks 50

Total Number of Lecture Hours 20 Exam Hours 03

Course Objectives

 To learn primitive constructs JAVA programming language.


 To understand Object Oriented Programming Features of JAVA.
 To gain knowledge on: packages, multithreaded programming and exceptions.
Prerequisites

➢ Basic knowledge of Programming


➢ Analytical and Logical thinking to analyze problem and deriving solution to problem

Course CO-PO-PSO Mapping

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.

Design a class involving 1-12 2 3 3 2 3 - - - 2 - - 2 2 - 2 2


data members and
methods for the given
CO2 scenario.

Apply the concepts of 1-12 2 3 3 2 3 - - - 2 - - 2 2 - 2 2


inheritance and interfaces
in solving real world
CO3 problems.

Use the concept of 1-12 2 3 3 2 3 - - - 2 - - 2 2 - 2 2


packages and exception
handling in solving
CO4 complex problem

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Apply concepts of 1-12 2 3 3 2 3 - - - 2 - 2 2 - - 2 2


multithreading,
autoboxing and
enumerations in program
CO5 development

CORRELATION
PROGRAM OUTCOMES (PO), PROGRAM SPECIFIC OUTCOMES (PSO)
LEVELS

PO1 Engineering knowledge PO7 Environment and sustainability 0 No Correlation

PO2 Problem analysis PO8 Ethics 1 Slight/Low

Moderate/
PO3 Design/development of solutions PO9 Individual and teamwork 2
Medium

Conduct investigations of complex


PO4 PO10 Communication 3 Substantial/ High
problems

PO5 Modern tool usage PO11 Project management and finance

PO6 The Engineer and society PO12 Life-long learning

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:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

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

 Familiarization with computer hardware and programming environment, concept of


naming the program files, storing, compilation, execution and debugging. Taking any
simple java code.

 Introduction about eclipse IDLE.

 Edit code on eclipse IDLE and save using filename.java

 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

a. Loop for j from 0 to num - 1:


i. Read an integer from the user and store it in matrix1[i][j].
Step-7: Print "Matrix 1 is :***** "
Step-8: Loop for i from 0 to num - 1:
a. Loop for j from 0 to num - 1:
i. Print matrix1[i][j] followed by a space.
b. Print a newline character.
Step-9: Print "-------------Enter values for matrix 2:---------------"
Step-10: Loop for i from 0 to num - 1:
a. Loop for j from 0 to num - 1:
i. Read an integer from the user and store it in matrix2[i][j].
Step-11: Print "Matrix 2 is :***** "
Loop for i from 0 to num - 1:
a. Loop for j from 0 to num - 1:
i. Print matrix2[i][j] followed by a space.
b. Print a newline character.
Step-12: Print "-----------After Addition Matrix will be ----------------"
Loop for i from 0 to num - 1:
a. Loop for j from 0 to num - 1:
i. Calculate Result[i][j] as the sum of matrix1[i][j] and matrix2[i][j].
ii. Print Result[i][j] followed by a space.
b. Print a newline character.
Step-13: End
*****************************************************************************
Program Code:
import java.util.Scanner;

public class Program1 {

public static void main(String[] args) {

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

// TODO Auto-generated method stub

System.out.println("Enter the number to create n*n matrix: ");


Scanner sc = new Scanner(System.in);
//int num = sc.nextInt();
int num = Integer.parseInt(args[0]); // Taking n from command line go to the run
configuration
//select argument tab and type the input then execute.
int matrix1 [][] = new int[num][num];
int matrix2 [][] = new int[num][num];
int Result[][] = new int[num][num];

System.out.println("Enter values for matrix 1:");


for(int i = 0; i <num; i++)
{
for(int j = 0; j< num; j++)
{
matrix1[i][j] = sc.nextInt();
}
}
System.out.println("****************Matrix 1 is :********************* ");
for(int i = 0; i <num; i++)
{
for(int j = 0; j< num; j++)
{

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


}
System.out.println();
}
System.out.println("-------------Enter values for matrix 2:---------------");
for(int i = 0; i <num; i++)
{
for(int j = 0; j< num; j++)
{
matrix2[i][j] = sc.nextInt();
}
}
System.out.println("****************Matrix 2 is :********************* ");
for(int i = 0; i <num; i++)
{
for(int j = 0; j< num; j++)
{

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

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


}
System.out.println();
}

System.out.println("-----------After Addition Matrix will be ----------------");


for(int i = 0; i <num; i++)
{
for(int j = 0; j< num; j++)
{
Result[i][j] = matrix1[i][j] + matrix2[i][j];

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


}
System.out.println();
}

}
******************************************************************************
Output:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Enter the number to create n*n matrix:


Enter values for matrix 1:
10
20
30
40
****************Matrix 1 is :*********************
10 20
30 40
-------------Enter values for matrix 2:---------------
10
20
30
40
****************Matrix 2 is :*********************
10 20
30 40
-----------After Addition Matrix will be ----------------
20 40
60 80

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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Print "Pushed: value."


Otherwise, print "Stack is full. Cannot push element value."
6. Define a method pop():
 Check if top is greater than or equal to 0 (stack is not empty):
 Get the value at array[top].
 Decrement top by 1.
 Print "Popped: value."
Otherwise, print "Stack is empty. Cannot pop."
7. Define a method display():
Check if top is greater than or equal to 0 (stack is not empty):
Print "Stack elements:".
Loop from i equal to top down to 0:
Print array[i].
Print a newline.
Otherwise, print "Stack is empty."
8. In the main method:
Create an instance of the Program2_Stack class.
Create a Scanner object for user input.
9. Create an infinite loop:
Display a menu:
"Press 1 for push"
"Press 2 for pop"
"Press 3 for display"
"Press 4 for exit"
10. Read the user's choice (ch) from input.
11. Use a switch statement to perform actions based on the user's choice:
Case 1: Push operation
Prompt the user for the number of values (n) to push.
Loop i from 0 to n - 1:
Prompt the user for the i+1th value and push it onto the stack.

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Case 2: Pop operation


Call the pop method to pop an element from the stack.
Case 3: Display operation
Call the display method to display the stack elements.
Case 4: Exit the program using System.exit(0).
12. End the loop.
******************************************************************************
Program Code:
import java.util.Scanner;

public class Program2_Stack {


private int[] array;
private int top;
private static final int MAX_SIZE = 10;

public Program2_Stack() {
array = new int[MAX_SIZE];
top = -1; // Initialize top as -1 to indicate an empty stack
}

// Method to push an element onto the stack


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

// Method to pop an element from the stack


public void pop() {
if (top >= 0) {
int poppedValue = array[top--];
System.out.println("Popped: " + poppedValue);
} else {
System.out.println("Stack is empty. Cannot pop.");
}
}
public void display() {
Department of Computer Science & Engineering, CMRIT, Bangalore
Java Programming Laboratory – BCS306A Academic Year: 2023-24

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

public static void main(String[] args) {


Program2_Stack stack = new Program2_Stack();
Scanner sc = new Scanner(System.in);

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

Press 1. for push 2 for pop 3. for display 4 for exit:


2
Popped: 30
Press 1. for push 2 for pop 3. for display 4 for exit:
3
Stack elements:
20
10

Press 1. for push 2 for pop 3. for display 4 for exit:


2
Popped: 20
Press 1. for push 2 for pop 3. for display 4 for exit:
2
Popped: 10
Press 1. for push 2 for pop 3. for display 4 for exit:
2
Stack is empty. Cannot pop.
Press 1. for push 2 for pop 3. for display 4 for exit:
3
Stack is empty.
Press 1. for push 2 for pop 3. for display 4 for exit:
4
******************************************************************************
Program 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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

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;

public class Employee {


private int id;
private String name;

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

private double salary;

// Constructor to initialize an Employee object


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

// Method to raise the salary by a given percentage


public void raiseSalary(double percent) {
if (percent > 0) {
salary += (salary * percent / 100.0);
System.out.println(name + "'s salary has been increased by " + percent + "%.");
} else {
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}

// Method to display employee information


public void displayInfo() {
System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: Rs." + salary);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter how many employee details you want to enter: ");
int n = sc.nextInt();

// Create an array of Employee objects


Employee[] emp = new Employee[n];

// Input employee details


for (int i = 0; i < n; i++) {
System.out.println("Enter Employee " + (i + 1) + " id: ");
int id = sc.nextInt();
System.out.println("Enter Employee " + (i + 1) + " name: ");
String name = sc.next();
System.out.println("Enter Employee " + (i + 1) + " salary: ");
double salary = sc.nextDouble();

emp[i] = new Employee(id, name, salary);

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

// Display initial employee information


System.out.println("Initial Employee Information:");
for (int i = 0; i < n; i++) {
emp[i].displayInfo();
System.out.println("----------------------------------------------------------------");
}

// Display information after increment


System.out.println("Enter increment %: ");
double percent = sc.nextDouble();
for (int i = 0; i < n; i++) {
emp[i].raiseSalary(percent);
}
System.out.println();
System.out.println("**********Employees Salary after increment:************ ");
System.out.println();
for (int i = 0; i < n; i++) {
emp[i].displayInfo();
System.out.println("----------------------------------------------------------------");

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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Employee Salary: Rs.40000.0


----------------------------------------------------------------
Employee ID: 102
Employee Name: rahul
Employee Salary: Rs.50000.0
----------------------------------------------------------------
Enter increment %:
20
rajni's salary has been increased by 20.0%.
rahul's salary has been increased by 20.0%.

**********Employees Salary after increment:************

Employee ID: 101


Employee Name: rajni
Employee Salary: Rs.48000.0
----------------------------------------------------------------
Employee ID: 102
Employee Name: rahul
Employee Salary: Rs.60000.0
----------------------------------------------------------------
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.
● 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.
***************************************************************************

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

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;

// Default constructor to create a point at (0, 0)


public MyPoint() {
this(0, 0);

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

// Overloaded constructor to create a point with given x and y coordinates


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

// Method to set both x and y


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

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


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

// Method to return a string description of the point in the format "(x, y)"
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}

// Method to calculate distance to another point with given (x, y) coordinates


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

// Method to calculate distance to another MyPoint instance


public double distance(MyPoint another) {
return distance(another.x, another.y);
}

// Method to calculate distance to the origin (0,0)


public double distance() {
return distance(0, 0);
}
}

public class Program4 {

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

public static void main(String[] args) {


MyPoint point1 = new MyPoint(3, 4);
MyPoint point2 = new MyPoint(6, 8);

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


System.out.println("Point 2: " + point2.toString());

System.out.println("Distance from Point 1 to (6, 8): " + point1.distance(6, 8));


System.out.println("Distance from Point 1 to Point 2: " + point1.distance(point2));
System.out.println("Distance from Point 1 to the origin: " + point1.distance());

// Testing setXY and getXY methods


point1.setXY(5, 10);
int[] coordinates = point1.getXY();
System.out.println("Point 1 after setXY(5, 10): " + point1.toString());
System.out.println("Coordinates of Point 1: (" + coordinates[0] + ", " + coordinates[1] + ")");
}
}
***************************************************************************
Output:

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:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

draw(): Display the message "Drawing a circle."


erase(): Display the message "Erasing a circle."
4. Create a subclass Triangle that extends Shape with two overridden methods:
draw(): Display the message "Drawing a triangle."
erase(): Display the message "Erasing a triangle."
5. Create a subclass Square that extends Shape with two overridden methods:
draw(): Display the message "Drawing a square."
erase(): Display the message "Erasing a square."
6. In the main method:
 Create an instance of Shape named shape1 and initialize it as a Circle.
 Create an instance of Shape named shape2 and initialize it as a Triangle.
 Create an instance of Shape named shape3 and initialize it as a Square.
7. Call the draw() and erase() methods on shape1, shape2, and shape3.
 For shape1, the output will be:
"Drawing a circle."
"Erasing a circle."
 For shape2, the output will be:
"Drawing a triangle."
"Erasing a triangle."
 For shape3, the output will be:
"Drawing a square."
"Erasing a square."
8. End the program.
***************************************************************************
Program Code:
// Shape class
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}

public void erase() {


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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

}
}

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

public class Program5_Shape {


public static void main(String[] args) {

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Shape shape1 = new Circle();


Shape shape2 = new Triangle();
Shape shape3 = new 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;

abstract class ShapePrg6 {


abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle1 extends ShapePrg6 {


private double radius;

public Circle1(double radius) {


this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}

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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

class Triangle1 extends ShapePrg6 {


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

public Triangle1(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@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() {
return side1 + side2 + side3;
}
}

public class Program6_Abstract_Class {


public static void main(String[] args) {
System.out.println("Enter radius: ");
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
Circle1 circle = new Circle1(r);
System.out.println("Enter side 1 :");
double a = sc.nextDouble();
System.out.println("Enter side 2 :");
double b = sc.nextDouble();
System.out.println("Enter side 3 :");
double c = sc.nextDouble();
Triangle1 triangle = new Triangle1(a,b,c);

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


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

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


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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

}
}
***************************************************************************
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.

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

 Display the message "Initial Dimensions:" followed by the initial dimensions of


the rectangle using the displayDimensions() method.
 Resize the width to 15 and the height to 8 using the resizeWidth() and
resizeHeight() methods, respectively.
 Display the message "Resized Dimensions after changing the height and width :"
followed by the updated dimensions using the displayDimensions() method.
5. End the program.
**************************************************************************
Program Code:
// Define the Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Implement the Resizable interface in the Rectangle class


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

public Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

public void displayDimensions() {


System.out.println("Width: " + width);
System.out.println("Height: " + height);
}
}

public class Program7_Interface_Concept {


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

// Display the initial dimensions


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

// Resize the width and height


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

// Display the resized dimensions


System.out.println("\nResized Dimensions after changing the height and width :");
rectangle.displayDimensions();
}
}
************************************************************************
Output:
Initial Dimensions:
Width: 10
Height: 5

Resized Dimensions after changing the height and width :


Width: 15
Height: 8
************************************************************************
Program 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.
************************************************************************
Algorithm:
1. Start the program.
Department of Computer Science & Engineering, CMRIT, Bangalore
Java Programming Laboratory – BCS306A Academic Year: 2023-24

2. Create an outer class named Outer:


 Define a method called display within the Outer class to display a message
specific to the outer class.
3. Inside the Outer class, create an inner class named Inner:
 Define a method called display within the Inner class to display a message
specific to the inner class.
4. In the Main class's main method:
 Create an instance of the Outer class called outer.
 Call the display method of the Outer class using the outer instance to display
the outer class's message.
 Create an instance of the Inner class using the outer instance and the new
keyword (i.e., outer.new Inner()).
 Call the display method of the Inner class using the inner instance to display
the inner class's message.
5. End the program.

***********************************************************************

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

public class Program8_InnerClass_Concept {


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

// Call the outer class's display method


outer.display();

// Create an instance of the inner class using the outer class's instance

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Outer.Inner inner = outer.new Inner();

// Call the inner class's display method


inner.display();
}
}
***********************************************************************
Output:
This is the outer class's display method.
This is the inner class's display method.
***********************************************************************
Program 9:
Develop a JAVA program to raise a custom exception (user defined exception) for DivisionByZero
using try, catch, throw and finally.
*****************************************************************************

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.

***********************************************************************

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

Program Code:
import java.util.Scanner;

// Custom exception class for DivisionByZero


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

public class Program9_UserDefinedException {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter divident: ");
int dividend = sc.nextInt();
System.out.println("Enter divisor: ");
int divisor = sc.nextInt();

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

int result = dividend / divisor;


System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
System.out.println("Exception caught: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Division by zero.");
} finally {
System.out.println("Finally block executed.");
}
}
}
***************************************************************************
Output:
Case1:
Enter divident:
20
Enter divisor:
0
Exception caught: Division by zero is not allowed.
Finally block executed.
Case 2:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

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:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

1. Created user defined package mypack


// File: mypack/MyClass.java
package mypack;

public class MyClass {


public void displayMessage() {
System.out.println("Hello from MyClass in mypack!");
}
}
2. Import package mypack.
// File: MyMainClass.java
import mypack.MyClass;

public class MyMainClass {


public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.displayMessage();
}
}
*******************************************************************
Output: Hello from MyClass in mypack!
************************************************************************
Program 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).
**************************************************************************
Algorithm:
1. Start the program.
2. Define a class MyRunnable that implements the Runnable interface:
 Create a constructor for MyRunnable that accepts a thread name as a
parameter.
 Implement the run method in MyRunnable:
 Display a message indicating the thread has started, including its
name.
 Sleep the thread for 500 milliseconds (0.5 seconds) using the
Thread.sleep(500) method. Handle the InterruptedException if it
occurs.
 Display a message indicating the thread is exiting, including its name.
3. In the main method:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

 Display a message indicating that the main thread is starting.


 Create three thread objects (thread1, thread2, and thread3) and associate each
with a new instance of the MyRunnable class, passing a unique thread name to
each constructor.
 Start each thread using the start() method.
 Use the join() method to wait for each thread (thread1, thread2, and thread3) to
finish executing.
 Display a message indicating that the main thread is exiting.
4. End the program.
**************************************************************************
Program Code:
class MyRunnable implements Runnable {
private String threadName;

public MyRunnable(String threadName) {


this.threadName = threadName;
}

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

public class Program11_RunnableExample {


public static void main(String[] args) {
System.out.println("Main thread is starting.");

// Create and start multiple threads using MyRunnable


Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
Thread thread3 = new Thread(new MyRunnable("Thread 3"));

// Start the threads


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

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

// Wait for the threads to finish


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

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


}
}
************************************************************************
Output:
Case 1:
Main thread is starting.
Thread Thread 1 is starting.
Thread Thread 3 is starting.
Thread Thread 2 is starting.
Thread Thread 1 is exiting.
Thread Thread 3 is exiting.
Thread Thread 2 is exiting.
Main thread is exiting.
Case 2:
Main thread is starting.
Thread Thread 2 is starting.
Thread Thread 1 is starting.
Thread Thread 3 is starting.
Thread Thread 2 is exiting.
Thread Thread 1 is exiting.
Thread Thread 3 is exiting.
Main thread is exiting.
**************************************************************************
Program 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.
**************************************************************************
Algorithm:
1. Start the program.
2. Define a class MyThread that extends the Thread class:

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

 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();
}

public void run() {


try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println("Child Thread interrupted.");
}
System.out.println("Child Thread exiting.");

Department of Computer Science & Engineering, CMRIT, Bangalore


Java Programming Laboratory – BCS306A Academic Year: 2023-24

}
}

public class Program12_ConcurrentExecution {


public static void main(String[] args) {
new MyThread(); // Create and start the child thread

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***************************************

Department of Computer Science & Engineering, CMRIT, Bangalore


OOPs With Java Lab

Extra Lab Program

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

String (Input string)

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

You might also like