[go: up one dir, main page]

0% found this document useful (0 votes)
13 views41 pages

Ooc Mannual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT

Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082


(Affiliated to Visvesvaraya Technological University, Belagavi
and Approved by AICTE, Accredited by NAAC A+, New Delhi)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


Accredited by NBA, New Delhi

2023-2024
III Semester CBCS
2022 scheme
OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY
Subject code: BCS306A

COMPILED BY:
Mrs. Shilpa V
Ms. Jahnavi S
Mr. Sumanth Reddy
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi & Approved By AICTE, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore-560082

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision and Mission of the Institution


Vision

“To strive at creating the institution a center of highest caliber of learning, so as to create an
overall intellectual atmosphere with each deriving strength from the other to be the best of the
engineers, scientists with management & design skills.”

Mission

• To serve its region, state, the nation and globally by preparing students to make
meaningful contributions in an increasing global society challenges.
• To encourage, reflection on and evaluation of emerging needs and priorities with the state
of art infrastructure at institution.
• To support research and services establishing enhancements in technical, economic,
human and cultural development.
• To establish inter disciplinary center of excellence, supporting/ promoting students
implementation.
• To increase the number of Doctorate holders to promote research culture in the campus.
• To increase IPC, IPR, EDC, innovation cells with functional MOU’s supporting students
quality growth.

Vision and Mission of the CSE Department


Vision

“Epitomize CSE graduate to crave a niche globally in the field of computer science to excel in
the world of information technology and automation by imparting knowledge to sustain skills for
the changing trends in the society and industry.”

Mission

• To educate students to become excellent engineers in a confident and creative


environment through world class pedagogy.
• Enhancing the knowledge in the changing technology trends by giving hands-on
experience through continuous education and by making them to organize & participate
in various events.
• Impart skills in the field of IT and its related areas with a focus on developing the required
competencies and virtues to meet the industry expectations.
• Ensure quality research and innovations to fulfil industry, government and social needs.
• Impart entrepreneurship and consultancy skills to students to develop self-sustaining life
skills in multi-disciplinary areas.
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi & Approved By AICTE, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore-560082

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Program Outcomes
a. Engineering Knowledge: Apply knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering
problems
b. Problem Analysis: Identify, formulate, research literature and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences
c. Design/ Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet specified needs with appropriate
consideration for public health and safety, cultural, societal and environmental considerations.
d. Conduct investigations of complex problems: Using research-based knowledge and
research methods including design of experiments, analysis and interpretation of data and
synthesis of information to provide valid conclusions.
e. Modern Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to Complex engineering activities
with an under- standing of the limitations.
f. The Engineer and Society: Apply reasoning informed by contextual knowledge to assess
societal, health, safety, legal and cultural issues and the Consequent responsibilities relevant
to professional engineering practice
g. Environment and Sustainability: Understand the impact of professional Engineering
solutions in societal and environmental contexts and demonstrate knowledge of and need for
sustainable development
h. Ethics: Apply ethical principles and commit to professional ethics and Responsibilities and
norms of engineering practice
i. Individual and Team Work: Function effectively as an individual, and as a member or leader
in diverse teams and in multi-disciplinary settings.
j. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as being able to comprehend and write
effective reports and design documentation, make effective presentations and give and receive
clear instructions.
k. Life-long Learning: Recognize the need for and have the preparation and ability to engage
in independent and life- long learning in the broadest context of technological change
l. Project Management and Finance: Demonstrate knowledge and understanding of engineering
and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multi-disciplinary environment
Program Specific Outcomes
m. PSO1: Adapt, Contribute Innovate ideas in the field of Artificial Intelligence and Machine
Learning
n. PSO2: Enrich the abilities to qualify for Employment, Higher studies and Research in various
domains of Artificial Intelligence and Machine Learning such as Data Science, Computer
Vision, Natural Language Processing with ethical values
o. PSO3: Acquire practical proficiency with niche technologies and open-source platforms and
become Entrepreneur in the domain of Artificial Intelligence and Machine Learning
List of
Experiments

Object Oriented Programming with JAVA


Course Code BCS306A CIE Marks 50
Teaching Hours/Week (L:T:P: S) 2:0:2 SEE Marks 50
Total Hours of Pedagogy 28T + 20P Total Marks 100
Credits 3 Exam Hours 03
Course Objectives:

CLO 1. Demonstrate the use of Eclipse/Netbeans IDE to create Java Applications.


CLO 2. Using java programming to develop programs for solving real-world problems
CLO 3.Reinforce the understanding of basic object-oriented programming concepts.

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


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

PART A – List of problems for which student should develop program and execute in the Laboratory

Programming Experiments (Suggested and are not limited to)

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:
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the default location of (0, 0).
● A overloaded constructor that constructs a point with the given x and y coordinates.
● A method setXY() to set both x and y.
● A method getXY() which returns the x and y in a 2-element int array.
● A toString() method that returns a string description of the instance in the format "(x, y)".
● A method called distance(int x, int y) that returns the distance from this point to another point at the
given (x, y) coordinates
● An overloaded distance(MyPoint another) that returns the distance from this point to the given
MyPoint instance (called another)
● Another overloaded distance() method that returns the distance from this point to the origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called TestMyPoint) to test all the
methods defined in the class.

5. Develop a JAVA program to create a class named shape. Create three sub classes namely: circle, triangle
and square, each class has two member functions named draw () and erase (). Demonstrate polymorphism
concepts by developing suitable methods, defining member data and main program.

6. Develop a JAVA program to create an abstract class Shape with abstract methods calculateArea() and
calculatePerimeter(). Create subclasses Circle and Triangle that extend the Shape class and implement
the respective methods to calculate the area and perimeter of each shape.
7. Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width) and
resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that implements the
Resizable interface and implements the resize methods

8. Develop a JAVA program to create an outer class with a function display. Create another class inside the
outer class named inner with a function called display and call the two functions in the main class.

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

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

11. Write a program to illustrate creation of threads using runnable class. (start method start each of the
newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds).

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.
Course Outcome (Course Skill Set)
At the end of the course the student will be able to:

CO 1. Understand the fundamental principles of object-oriented programming in Java, encompassing abstraction


and the three OOP principles.
CO 2. Apply Java's data types, variables, and arrays effectively, including primitive types and type conversion, to
solve practical problems.
CO 3. Analyze and optimize Java code by using operators, control statements, and decision-making constructs to
solve complex problems, ensuring code efficiency
CO 4. Design and implement Java applications for specific lab experiments that relate to the course content,
while also creating them to develop robust and responsive software solutions.
CO 5. Develop and evaluate Java applications for lab experiments, focusing on advanced topics like
multithreading, exceptions, and synchronization, to create robust and responsive software solutions that align
with the course objectives and experimental requirements..
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the SEE
minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall be deemed to
have satisfied the academic requirements and earned the credits allotted to each subject/ course if the
student secures a minimum of 40% (40 marks out of 100) in the sum total of the CIE (Continuous Internal
Evaluation) and SEE (Semester End Examination) taken together.

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)
Suggested Learning Resources:

Textbook

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.

2. Thinking in Java, Fourth Edition, by Bruce Eckel, Prentice Hall, 2006


(https://sd.blackball.lv/library/thinking_in_java_4th_edition.pdf)
Web links and Video Lectures (e-Resources):

1. Java Tutorial: https://www.geeksforgeeks.org/java/


2. Introduction To Programming In Java (by Evan Jones, Adam Marcus and Eugene Wu):
3. https://ocw.mit.edu/courses/6-092-introduction-to-programming-in-java-january-iap-2010/
4. Java Tutorial: https://www.w3schools.com/java/
Java Tutorial: https://www.javatpoint.com/java-tutorial
Activity Based Learning (Suggested Activities)/ Practical Based learning
1. Installation of Java (Refer: https://www.java.com/en/download/help/index_installing.html)
2. Demonstration of online IDEs like geeksforgeeks, jdoodle or any other Tools
3. Demonstration of class diagrams for the class abstraction, type visibility, composition and
inheritance

Assessment Method
● Programming Assignment / Course Project
OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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

PROGRAM :
public class MatrixAddition {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide the order N as a command line argument.");
return;
}

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

if (N <= 0) {
System.out.println("N should be a positive integer.");
return;
}

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


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

// Initialize the matrices with some sample values


initializeMatrix(matrixA, N);
initializeMatrix(matrixB, N);

// Add the matrices


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
}

Dept. of CSE DSATM, Bengaluru Page 7


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

// Display the result matrix


System.out.println("Matrix A:");
displayMatrix(matrixA, N);

System.out.println("Matrix B:");
displayMatrix(matrixB, N);

System.out.println("Result Matrix (A + B):");


displayMatrix(resultMatrix, N);
}

// Initialize a matrix with sample values


private static void initializeMatrix(int[][] matrix, int N) {
int value = 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = value++;
}
}
}

// Display a matrix
private static void displayMatrix(int[][] matrix, int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Dept. of CSE DSATM, Bengaluru Page 8


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

OUT PUT:
Provide Command Line Arguments:

In the "Console" view at the bottom, you should see your program running.
In the "Console," you can provide the value of N as a command line argument by going to the
"Run" menu (in the console) and selecting Run Configurations.
In the "Arguments" tab, you can add your desired value for N.
Click "Run": Once you've provided the command line argument, click the "Run" button.

View the Output:

The program will execute, and you'll see the output in the Console view within Eclipse.
Please replace <N> in the command line argument with the actual value of N you want to use when
running the program in Eclipse. The output will vary depending on the value of N and the random
sample values used to initialize the matrices in the code.

These steps should help you run the Java program successfully in Eclipse.

Matrix A:
123
456
789

Matrix B:
987
654
321

Result Matrix (A + B):


10 10 10
10 10 10
10 10 10

Dept. of CSE DSATM, Bengaluru Page 9


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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.

PROGRAM :

class Stack {
private int[] stackArray;
private int top;
private int capacity;

public Stack(int capacity) {


this.capacity = capacity;
this.stackArray = new int[capacity];
this.top = -1;
}

public void push(int value) {


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

public int pop() {


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

Dept. of CSE DSATM, Bengaluru Page 10


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

public int peek() {


if (top >= 0) {
int value = stackArray[top];
System.out.println("Peeked: " + value);
return value;
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1;
}
}

public boolean isEmpty() {


return top == -1;
}

public boolean isFull() {


return top == capacity - 1;
}
}
public class StackDemo {
public static void main(String[] args) {
Stack stack = new Stack(10);
stack.push(5);
stack.push(10);
stack.push(15);

stack.pop();
stack.pop();

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

stack.peek();

while (!stack.isEmpty()) {
stack.pop();
}
}
}

Dept. of CSE DSATM, Bengaluru Page 11


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

OUTPUT:

Pushed: 5
Pushed: 10
Pushed: 15
Popped: 15
Popped: 10
Pushed: 20
Pushed: 25
Peeked: 25
Popped: 25
Popped: 20
Popped: 5

Dept. of CSE DSATM, Bengaluru Page 12


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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 salary by
the given percentage. Develop the Employee class and suitable main method for demonstration

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

public Employee(int id, String name, double salary) {


this.id = id;
this.name = name;
this.salary = salary;
}

public void raiseSalary(double percent) {


salary = salary * (1 + percent / 100);
}

public void display() {


System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: $" + salary);
}
}

public class EmployeeDemo {


public static void main(String[] args) {
Employee employee = new Employee(1, "John", 50000);

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


employee.display();

// Raise salary by 10%


employee.raiseSalary(10);

Dept. of CSE DSATM, Bengaluru Page 13


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

System.out.println("\nEmployee Details After Salary Raise:");


employee.display();
}
}

OUTPUT:

Initial Employee Details:


Employee ID: 1
Employee Name: John
Employee Salary: $50000.0

Employee Details After Salary Raise:


Employee ID: 1
Employee Name: John
Employee Salary: $55000.00000000001

Dept. of CSE DSATM, Bengaluru Page 14


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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

PROGRAM :

class MyPoint {
private int x;
private int y;

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

public MyPoint(int x, int y) {


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

public void setXY(int x, int y) {


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

Dept. of CSE DSATM, Bengaluru Page 15


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

public int[] getXY() {


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

public double distance(int x, int y) {


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

public double distance(MyPoint another) {


int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
public double distance()
{ return distance(0,
0); }
@Override
public String toString() {

return "(" + x + ", " + y + ")";


}
}

public class TestMyPoint {


public static void main(String[] args) {
MyPoint point1 = new MyPoint();

MyPoint point2 = new MyPoint(3, 4);


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

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

int[] coordinates = point2.getXY();

Dept. of CSE DSATM, Bengaluru Page 16


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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

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


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

}
}
OUTPUT

Point 1: (0, 0)

Point 2: (3, 4)

Point 1 after setXY(1, 2): (1, 2)

Coordinates of Point 2: (3, 4)

Distance from Point 1 to (5, 6): 5.656854249492381

Distance from Point 1 to Point 2: 2.8284271247461903

Distance from Point 1 to the origin: 2.23606797749979

Dept. of CSE DSATM, Bengaluru Page 17


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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

PROGRAM

class Shape
{
void draw()
{

System.out.println("Shape draw()");
}
void erase()
{
System.out.println("Shape erase()");
}
}

class Circle extends Shape


{
void draw()
{
System.out.println("Circle draw()");
}
void erase()
{
System.out.println ("Circle erase()");
}
}

Dept. of CSE DSATM, Bengaluru Page 18


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

class Triangle extends Shape


{
void draw()
{
System.out.println("Triangle draw()");
}
void erase()
{
System.out.println("Triangle erase()");
}
}

class Square extends Shape


{
void draw()
{
System.out.println("Square draw");
}
void erase()
{
System.out.println("Square erase)");
}
}

public class Polyshape


{
public static void main (String arg[])
{
Shape s =new Shape();
s.draw();
s.erase();

s = new Circle();
s.draw();
s.erase();

Dept. of CSE DSATM, Bengaluru Page 19


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

s = new Triangle();
s.draw();
s.erase();

s = new Square();
s.draw();
s.erase();

}
}

Output

Shape draw()
Shape erase()
Circle draw()
Circle erase()
Triangle draw()
Triangle erase()
Square draw
Square erase)

Dept. of CSE DSATM, Bengaluru Page 20


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

PROGRAM :6

PROGRAM
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

abstract class Shape {


abstract double calculateArea();
abstract double calculatePerimeter();
}
class Circle extends Shape {
private double radius;

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

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

double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Triangle extends Shape {
private double side1;
private double side2;
private double side3;

public Triangle(double a, double b, double c) {


this.side1 = a;
this.side2 = b;

Dept. of CSE DSATM, Bengaluru Page 21


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

this.side3 = c;
}
double calculateArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
public class AbstractShape {
public static void main(String[] args) {

double r = 4.0;
Circle circle = new Circle(r);

double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;


Triangle triangle = new Triangle(ts1, ts2, ts3);

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


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

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


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

Output
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345
Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0

Dept. of CSE DSATM, Bengaluru Page 22


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

PROGRAM :7

PROGRAM

Develop a JAVA program to create an interface Resizable with methods resizeWidth(int width)
and resizeHeight(int height) that allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize methods

interface Resizable {

void resizeWidth(int width);


void resizeHeight(int height);
}

class Rectangle implements Resizable {

private int width;


private int height;

public Rectangle(int w, int h) {


this.width = w;
this.height = h;
}

public void resizeWidth(int w) {


this.width = w;
}

public void resizeHeight(int h) {


this.height = h;
}

public void printSize() {


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

Dept. of CSE DSATM, Bengaluru Page 23


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

}
}
public class InterfaceRectangle {
public static void main(String[] args) {

Rectangle rectangle = new Rectangle(10, 15);

rectangle.printSize();

rectangle.resizeWidth(150);
rectangle.resizeHeight(200);

rectangle.printSize();
}
}

Output
Width: 10, Height: 15
Width: 150, Height: 200

Dept. of CSE DSATM, Bengaluru Page 24


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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.

PROGRAM

class Outer
{
String msgOuter = "This is Outer Class";
void display()
{
System.out.println(msgOuter);
}

void test(){
Inner inner = new Inner();
inner.display();
}

class Inner
{
String msgInner ="This is inner Class";
void display()
{
System.out.println(msgInner);
}
}
}
class InnerClassDeml
{
public static void main(String args[])
{
Outer outer = new Outer();

Dept. of CSE DSATM, Bengaluru Page 25


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

outer.display();
outer.test();
}
}

Output
This is Outer Class
This is inner Class

Dept. of CSE DSATM, Bengaluru Page 26


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

PROGRAM :9

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

PROGRAM

import java.util.*;
public class TryP
{
int c;
void div(int a,int b)
{
try
{
c=a/b;
System.out.println("Result="+c);
}
catch(ArithmeticException e)
{
System.out.println("Cannot divide by zero");
}
}
public static void main(String args[])
{
TryP obj=new TryP();
Scanner in=new Scanner(System.in);
System.out.println("Enter the values of a and b");
int no1=in.nextInt();
int no2=in.nextInt();
obj.div(no1,no2); }}

Dept. of CSE DSATM, Bengaluru Page 27


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

Output:

Enter the values of a and b

20

Cannot divide by zero

Dept. of CSE DSATM, Bengaluru Page 28


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

PROGRAM :10

Develop a JAVA program to create a package named mypack and import & implement it in a
suitable class.
Aim: Develop a java application to implement currency converter (Dollar to INR, EURO to
INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice
versa), time converter (hours to minutes, seconds and vice versa) using packages.

PROGRAM
CurrencyC.java
package cc;
import java.util.*;
public class CurrencyC
{
double inr,usd;
double euro,yen;
Scanner in=new Scanner(System.in);
public void dollartorupee()
{
System.out.println("Enter dollars to
convert into Rupees:");
usd=in.nextInt();
inr=usd*81.83;
System.out.println("Dollar ="+usd+" equal to INR="+inr);
System.out.println("\n");
}
public void rupeetodollar()
{
System.out.println("Enter Rupee to convert into Dollars:");
inr=in.nextInt();
usd=inr/81.83;
System.out.println("Rupee ="+inr+"equal to Dollars="+usd);
}

Dept. of CSE DSATM, Bengaluru Page 29


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

public void eurotorupee()


{
System.out.println("Enter Euro to convert into Rupees:");
euro=in.nextInt();
inr=euro*79.06;
System.out.println("Euro ="+euro+" equal to INR="+inr);
System.out.println("\n");
}
public void rupeetoeuro()
{
System.out.println("Enter Rupees to convert into Euro:");
inr=in.nextInt();
euro=(inr/79.06);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
System.out.println("\n");
}
public void yentoruppe()
{
System.out.println("Enter Yen to convert into Rupees:");
yen=in.nextInt();
inr=yen*0.57;
System.out.println("Yen ="+yen+" equal to INR="+inr);
System.out.println("\n");
}
public void ruppetoyen()
{
System.out.println("Enter Rupees to convert into Yen:");
inr=in.nextInt();
yen=(inr/0.57);
System.out.println("INR="+inr +"equal to YEN"+yen);
System.out.println("\n"); } }

Dept. of CSE DSATM, Bengaluru Page 30


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

DistaceC.Java

package dc;
import java.util.*;
public class DistanceC
{
double km,m,miles;
Scanner in=new Scanner(System.in);
public void mtokm()
{
System.out.println("Enter the distance in meter");
m=in.nextDouble();
km=(m/1000);
System.out.println(m+"m" +" is equal to +km+"km");
System.out.println("\n");
}
public void kmtom()
{
System.out.println("Enter the distance in Kilometer");
km=in.nextDouble();
m=km*1000;
System.out.println(km+"km" +" is equal to "+m+"m");
System.out.println("\n");
}
public void milestokm()
{
System.out.println("Enter the distance in miles");
miles=in.nextDouble();
km=(miles*1.60934);
System.out.println(miles+"miles" +" is equal to "+km+"km");
System.out.println("\n"); }

Dept. of CSE DSATM, Bengaluru Page 31


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

public void kmtomiles()


{
System.out.println("Enter the distance in km");
km=in.nextDouble();
miles=(km*0.621371);
System.out.println(km+"km" +" is equal to "+miles+"miles");
}
}

TimeC.java
package tc;
import java.util.*;
public class TimeC
{
int hours,seconds,minutes;
Scanner in = new Scanner(System.in);

public void hourstominutes()


{
System.out.println("Enter the no of Hours to convert into minutes");
hours=in.nextInt();
minutes=(hours*60);
System.out.println("Minutes: " + minutes);
}
public void minutestohours()
{
System.out.println("Enter the no of Minutes to convert into Hours");
minutes=in.nextInt();
hours=minutes/60;
System.out.println("Hours: " + hours);
}

Dept. of CSE DSATM, Bengaluru Page 32


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

public void hourstoseconds()


{
System.out.println("Enter the no of Hours to convert into Seconds");
hours=in.nextInt();
seconds=(hours*3600);
System.out.println("Seconds: " + seconds);
}
public void secondstohours()
{
System.out.println("Enter the no of Seconds to convert into Hours");
seconds=in.nextInt();
hours=seconds/3600;
System.out.println(seconds+"seconds"+ " is equal to "+hours+"hour");
}
}

Main Class
import cc.*;
import dc.*;
import tc.*;
public class Main
{
public static void main(String args[])
{
CurrencyC obj=new CurrencyC();
DistanceC obj1=new DistanceC();
TimeC obj2=new TimeC();
obj.dollartorupee();
obj.rupeetodollar();
obj.eurotorupee();

Dept. of CSE DSATM, Bengaluru Page 33


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

obj.rupeetoeuro();
obj.yentoruppe();
obj.ruppetoyen();
obj1.mtokm();
obj1.kmtom();
obj1.milestokm();
obj1.kmtomiles();
obj2.hourstominutes();
obj2.minutestohours();
obj2.hourstoseconds();
obj2.secondstohours();
}
}
OUTPUT:
Enter dollars to convert into Rupees:1
Dollar =1.0 equal to INR=81.83
Enter Rupee to convert into Dollars: 80
Rupee =80.0equal to Dollars=0.977636563607479
Enter the distance in meter :1000
1000.0m is equal to 1.0km
Enter the distance in Kilometre :1
1.0km is equal to 1000.0m
Enter the no of Hours to convert into minutes: 1
Minutes: 60
Enter the no of Minutes to convert into Hours: 60
Hours: 1

Dept. of CSE DSATM, Bengaluru Page 34


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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

PROGRAM

import java.util.Random;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{
x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );

Dept. of CSE DSATM, Bengaluru Page 35


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

}
}
class Rnumber extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<5; i++)
{
int randomInteger = random.nextInt(10);
System.out.println("Random Integer generated : " + randomInteger);
Square s = new Square(randomInteger);
s.start();
Cube c = new Cube(randomInteger);
c.start();
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println(ex);
}
}
}
}
public class ThreadP
{
public static void main(String[] args)
{
Rnumber n = new Rnumber();

Dept. of CSE DSATM, Bengaluru Page 36


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

n.start();
}
}
Output:

Random Integer generated : 7


Square of 7 = 49
Cube of 7 = 343
Random Integer generated : 8
Square of 8 = 64
Cube of 8 = 512
Random Integer generated : 4
Square of 4 = 16
Cube of 4 = 64
Random Integer generated : 8
Square of 8 = 64
Cube of 8 = 512
Random Integer generated : 3
Square of 3 = 9
Cube of 3 = 27

Dept. of CSE DSATM, Bengaluru Page 37


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

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.

PROGRAM

class MyThread extends Thread {


public MyThread() {
super(); // Calls the constructor of the base Thread class
}

@Override
public void run() {
// Code to be executed by the child thread
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class Main {


public static void main(String[] args) {
MyThread myThread = new MyThread(); // Create an instance of MyThread
myThread.start(); // Start the child thread

Dept. of CSE DSATM, Bengaluru Page 38


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

// Code to be executed by the main thread


for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
Output:

Main Thread: 1
Child Thread: 1
Main Thread: 2
Child Thread: 2
Main Thread: 3
Child Thread: 3
Main Thread: 4
Child Thread: 4
Main Thread: 5
Child Thread: 5

Dept. of CSE DSATM, Bengaluru Page 39


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

VIVA QUESTIONS

1. What is the difference between OOP and SOP?


2. What is OOPs?
3. Why use OOPs?
4. What are the main features of OOPs?
5. What is an object?
6. What is a class?
7. What is the difference between a class and a structure?
8. Can you call the base class method without creating an instance?
9. What is the difference between a class and an object?
10. What is inheritance?
11. What are the different types of inheritance?
12. What is the difference between multiple and multilevel inheritance?
13. What is hybrid inheritance?
14. What is hierarchical inheritance?
15. What are the limitations of inheritance?
16. What is a superclass?
17. What is a subclass?
18. What is polymorphism?
19. What is static polymorphism?
20. What is dynamic polymorphism?
21. What is method overloading?
22. What is method overriding?
23. What is operator overloading?
24. Differentiate between overloading and overriding.
25. What is encapsulation?
26. What are ‘access specifiers’?
27. What is the difference between public, private and protected access modifiers?
28. What is data abstraction?
29. How to achieve data abstraction?
30. What is an abstract class?
31. Can you create an instance of an abstract class?
32. What is an interface?
33. Differentiate between data abstraction and encapsulation.

Dept. of CSE DSATM, Bengaluru Page 40


OOP with Java / BCS306A
OOP with Java Lab /21CSL35

34. What are virtual functions?


35. What are pure virtual functions?
36. What is a constructor?
37. What is a destructor?
38. Types of constructors
39. What is a copy constructor?
40. What is the use of ‘finalize’?
41. What is Garbage Collection(GC)?
42. Differentiate between a class and a method.
43. Differentiate between an abstract class and an interface?
44. What is a final variable?
45. What is an exception?
46. What is exception handling?
47. What is the difference between an error and an exception?
48. What is a try/ catch block?
49. What is a finally block?

Dept. of CSE DSATM, Bengaluru Page 41

You might also like