0% found this document useful (0 votes)
30 views75 pages

Lab Manual Ooj

Uploaded by

jayanthss2345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views75 pages

Lab Manual Ooj

Uploaded by

jayanthss2345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

SUBRAMANYA EDUCATION SOCIETY [R]

EAST WEST INSTITUTE OF TECHNOLOGY


(Affiliated to VTU, Belagavi, Approved by AICTE, New Delhi & Recognized by Govt. of Karnataka) #63 Off Magadi
Road, Vishwaneedham Post, Bengalore-91

DEPARTMENT OF COMPUTER
SCIENCE AND ENGINEERING

LABORATORY MANUAL

B.E III SEMESTER(CBCS SCHEME)

OBJECT ORIENTED PROGRAMMING WITH JAVA [BCS306A]

[Type text] Page 1


PREFACE
Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism etc. in programming.

The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.

The manual of Object-oriented programming has been prepared for B.E Artificial
intelligence and machine learning students. Object-oriented programming is
increasingly becoming top priority choice of IT industry especially industries involve
in software development at system level.

The manual prepared for proper development of Java skills among the students. The
manual contains programs and their solutions for easy and quick understanding of
students

Dr. Achyutha Prasad N


Department of Computer Science and Engineering

ABOUT
The Department of Computer Science and Engineering was established in the year 2021.The department
offer undergraduate in Computer Science and Engineering. The department has a very good
infrastructure and faculty to provide excellent education to meet the industry standards.

Today, the department caters to the needs of more than 180 UG students. It houses state of the art
computing facilities with high end servers which support the LAN, provide a Linux/Unix environment,
also provides exclusive library facility to its students and boasts of well trained and experienced faculty
teaching the departments various courses in the areas of Computer Networks, Computer Architecture,
Database Systems, Microcontroller, Operating Systems, Design and Analysis of Algorithms and
Software Engineering.

The department lays stress on the practical and application-based aspects through laboratories, seminars,
group discussions, viva-voce and project work, keeping pace with the growth in Computer Science &
Engineering and AI technology.

Students are provided with opportunities to conduct experiments on innovative ideas, blending sound the
or ethical knowledge with practical experience. This comprehensive approach prepares them for a broad
spectrum of challenging roles in the field of Computer Science & Engineering and AI, including:

System Software Development


Application Software
Development Computer
Networking
EAST WEST INSTITUTE OF TECHNOLOGY

Department of Computer Science and


Engineering

[Type text]

Page 4
PROGRAM OUTCOMES

[Type text]

Page 5
EAST WEST INSTITUTE OF TECHNOLOGY
Department of Computer Science and Engineering

LABORATORY MANUAL (2023-2024)


Data Structures and Applications Laboratory
(BCS306A)
FOR
B.E III SEMESTER

Prepared by,

Prof. Vishaka Rani


Assistant Professor
Dept of CSE

[Type text]

Page 6
Object Oriented Program Programming with java

COURSE DETAILS
Course Name: Oriented Programming with JAVA Laboratory
Course Code:
BCS306A Course
Credit: 2

COURSE OBJECTIVE
1. To learn primitive constructs JAVA programming language.
2. To understand Object Oriented Programming Features of JAVA.
3. To gain knowledge on: packages, multithreaded programming and exceptions.

COURSE OUTCOME
BCS306A -1. Demonstrate proficiency in writing simple programs involving branching and looping
structures.
BCS306A -2. Design a class involving data members and methods for the given scenario.
BCS306A -3. Apply the concepts of inheritance and interfaces in solving real world
problems. BCS306A -4. Use the concept of packages and exception handling in solving
complex problem
BCS306A -5. Apply concepts of multithreading, autoboxing and enumerations in program development

CO-PO&PSOMAPPING

COURSE P P P P P P P P P PO PO PO
OUTCO O1 O2 O3 O O5 O6 O7 O8 O9 10 11 12
ME
4
BCS306A 3 3 3 -- 3 -- -- -- 3 2 -- 3
.1
BCS306A 3 3 3 -- 3 -- -- -- 3 2 -- 3
.2
BCS306A 3 3 3 2 3 -- -- -- 3 2 -- 3
.3
BCS306A 3 3 3 2 3 -- -- -- 3 3 2 3
.4
BCS306A 3 3 3 2 3 -- -- -- 3 2 2 3
.5
OOJ P P P P P P P P P PO PO PO
Object Oriented Program Programming with java
Laborator O1 O2 O3 O O5 O6 O7 O8 O9 10 11 12
y
BCS30 4
6A
3 3 3 2 3 -- -- -- 3 2 2 3
Object Oriented Program Programming with java

COURSE PSO PSO2 PSO3


OUTCOME 1
CO1 2 - -
- -
CO2 -- - -
- -
CO3 2 2 2
CO4 2 2 2
CO5 2 2 2
OOJ PSO PSO2 PSO2
Laboratory
1
BCS306A
2 2 2

LAB EVALUATION PROCESS

WEEK WISE EVALUATION OF EACH


PROGRAM
SL.N ACTIVITY MARKS
O
1 Record 5

2 Program 5
Execution
TOTAL 1
0

INTERNAL ASSESSMENT EVALUATION (End of


Semester)
SL.N ACTIVITY MARKS
O
1 Write- 1
Up 0
2 Execution 1
0
3 Result 5
Verification
3 Viva Voce 5
TOTA 3
L 0
Object Oriented Program Programming with java

FINAL INTERNAL ASSESSMENT


CALCULATION
SL.N ACTIVITY MAR
O KS
1 Average of Weekly 10
Entries
Average of internal
2 30
Assessment
TOTAL 40
Object Oriented Program Programming with java

Lab Rubrics

Students’ performance in Laboratory course is evaluated using rubrics defined by the program.
Rubrics for evaluating a lab test in programming lab are displayed in the following table.

Sl Evaluati Very Good Satisfactory Weak


. on Good
N Paramet
o. ers
1 Writing Program 10-9 8-6 5-3 Marks 2-0
[Max. Marks Marks Marks Marks
10] Completeness of Completeness of Completeness of Lack of
code, consistent code, consistent code, inconsistent completeness of
variable naming and variable naming and variable naming code, improper
formatting, well formatting, lack of and formatting, variable naming and
commented, uses comments, uses lacks clarity in not formatted, lacks
existing skills in new existing skills in new commenting, uses comments, uses
ways/learns new ways/learns new existing skills to existing skills to
skills to solve the skills to solve the solve the partially solve the
experimental experimental experimental experimental
problem. problem. problem. problem.

2 Program 10-9 8-6 5-3 Marks 2-0


Execution Marks Marks Marks
[Max. Marks
10] Program is free of Program is free of Program is free of Program contains
errors and output is errors and output is errors and output is few logical errors
well formatted. well formatted. not properly and output is not
Demonstrates Demonstrates better formatted. formatted.
excellent problem problem solving and Demonstrates a Demonstrates partial
solving and creativity creativity skills. clear understanding of the
skills. understanding of concepts relevant to
the concepts the experiment.
relevant to the
experiment.
3 Program 5 -4 3 2 Marks 1
Modification Marks Marks Marks
and verify the Able to modify the Able to modify the Able to modify the Unable to modify
results [Max. changes specified changes specified changes specified the changes
Marks 5] and test the output. with help could test with help could test specified and
the output. the output. unable to test the
output.
4 Viva-Voice 5-4 3 2 Marks 1
[Max. Marks Marks Marks Marks
5] Answers all the Answer 80% of the Answer 50% of Couldn’t answer
viva questions. viva questions. the viva viva questions
questions. properly.

Table 1: Rubrics for Lab Test Evaluation


Object Oriented Program Programming with java

Student’s ability in developing programs and testing the program, documenting the work done
through lab record, etc are evaluated continuously during all lab sessions.

Sl Evaluati Very Good Go Satisfactory We


. on od ak
N Paramet
o. ers
1 Record and 5 -4 Marks 3 Marks 2 Marks 1 Marks
Observation Neatly written the Neatly written the Lack of neatness in Data are missing and
[Max. Marks 5] record and regular to record, some data are the record, some not written record
data
lab missing in the record. are missing in the neatly and irregular
to
Student is regular to record. Student is lab
lab.
regular to lab
2 Program 5 -4 Marks 3 Marks 2 Marks 1 Marks
Execution
and viva Program is free of Program is free of Program is free of Program contains few
[Max. Marks 5] errors and output is errors and output is errors and output is logical errors and
well well
formatted. formatted. not properly output is not
formatted.
Answer all viva Answer 80% of the formatted. Couldn’t answer viva
viva
questions questions. Answer 50% of the questions properly.
viva questions.

Table 2: Rubrics for continuous Evaluation in lab


Object Oriented Program Programming with java

SYLLABUS

Course Code: BCS306A IA Marks 50


No. of Practical Hrs: 0:2:2
Total No. of Practical Hrs

LIST OF PROGRAMS
Sl.N Name of the COS POS
o experiments
1 Develop a JAVA program to add TWO matrices of suitable order CO1 PO1,P
N (The value of N should be read from command line 02,
arguments). PO3
2 Develop a stack class to hold a maximum of 10 integers CO1 PO1,PO2,PO
with suitable methods. Develop a JAVA main method to 3
illustrate Stack operations.

3 A class called Employee, which models an employee with an ID, CO1 PO1,PO2,PO
name and salary, is designed as shown in the following class 3
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 CO2 PO1,P
coordinates, is designed as follows: O2,
● Two instance variables x (int) and y (int).
● A default (or "no-arg") constructor that construct a point at the PO3
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.
Object Oriented Program Programming with java

5 Develop a JAVA program to create a class named shape. CO2 PO1,P


Create three sub classes namely: circle, triangle and square, O2,
each class has two member functions named draw () and PO3,P
erase ().
Demonstrate 15.09.2023 14.09.2023 Annexure-II 3 3 O4
polymorphism concepts by developing suitable methods,
defining member data and main program
6 Develop a JAVA program to create an abstract class Shape CO1 PO1,PO2,P
with abstract methods calculateArea() and calculatePerimeter(). O3
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 CO1 PO1,PO2,P


with methods resizeWidth(int width) and resizeHeight(int O3
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 CO1 PO1,PO2,P
display. Create another class inside the outer class named inner O3
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 CO2 PO1,P


defined exception) for DivisionByZero using try, catch, throw O2,
and finally
PO3,P
O4
10 Develop a JAVA program to create a package named mypack CO3 PO2,
and import & implement it in a suitable class. PO3,P
O5
11 Write a program to illustrate creation of threads using CO3 PO2,
runnable class. (start method start each of the newly created PO3,P
thread. Inside the run method there is sleep() for suspend the
O5
thread for 500 milliseconds).
12 Develop a program to create a class MyThread in this class a C04 PO2,
constructor, call the base class constructor, using super and start the PO3,PO
thread. The run method of the class starts after this. It can be 12
observed that both main thread and created child thread are
executed concurrently.
Object Oriented Program Programming with java

Step 0: Launch Eclipse


1. Launch Eclipse by running "eclipse.exe" from the Eclipse installed directory.
2. Choose an appropriate directory for your workspace, i.e., the directory (or folder) that you would like to
save your files (e.g., c:\myProject\eclipse_workspace for Windows) ⇒ Launch.
3. If the "Welcome" screen shows up, close it by clicking the "close" button next to the "Welcome" title.

Step 1: Create a new "Java Project"


For each Java application, you need to create a project to keep all the source files, classes and relevant
resources. To create a new "Java project":
1. Choose "File" menu ⇒ "New" ⇒ "Java project" (or "File" ⇒ "New" ⇒ "Project" ⇒ "Java project").
2. The "New Java Project" dialog pops up.
a. In "Project name", enter
"FirstProject". b.Check "Use default
location".
c. In "JRE", select "Use default JRE 'jre' and workspace compiler preferences".
d. In "Project Layout", check "Use project folder as root for sources and class files".
e. In "Module", UNCHECK "Create module-info.java"
file. Push "Finish" button.
3. IF "Create module-info.java" dialog appears, Click "Don't Create" (This will not appear if you do step2.

Step 3: Compile & Execute the Java Program


1. There is no need to compile the Java source file in Eclipse explicitly. It is because Eclipse performs the so-
called incremental compilation, i.e., the Java statement is compiled as and when it is entered.
2. To run the program, right-click anywhere on the source file "Hello.java" (or choose "Run" menu) ⇒ Run As
⇒ Java Application.
3. The output "Hello, world!" appears on the Console pane (the bottom pane).
Object Oriented Program Programming with java

PROGRAMS

1. Develop a JAVA program to add TWO matrices of suitable order N (The value
of N should be read from command line arguments).
// Java program for addition of two
matrices import java.io.*;
class GFG {
// Function to print Matrix
static void printMatrix(int
M[][], int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i+
+) { for (int j = 0; j <
colSize; j++)
System.out.print(M[i][j] + "
"); System.out.println();
}
}
// Function to add the two matrices
// and store in matrix C
static int[][] add(int A[][], int
B[][], int size)
{
int i, j;
int C[][] = new int[size]
[size]; for (i = 0; i < size;
i++)
for (j = 0; j < size; j+
+) C[i][j] = A[i][j] +
B[i][j];
return C;
}

// Driver code
public static void main(String[] args)
{
int size = 4;
int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix
A:"); printMatrix(A, size,
size);
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
Object Oriented Program Programming with java
{ 3, 3, 3, 3 },

{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix
B:"); printMatrix(B, size,
size);
// Add the two matrices
int C[][] = add(A, B, size);
// Print the result System.out.println("\
nResultant Matrix:"); printMatrix(C,
size, size);
}
}
Output:

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)


Object Oriented Program Programming with java
● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

ALGORITHM:

Steps to implement the algorithm:


1. Read the value of N (the size of the matrix) from the command line argument.
2. Read the elements of the first matrix (of size N×N) from the user.
3. Read the elements of the second matrix (of size N×N) from the user.
4. Add the two matrices element-wise to produce a result matrix.
5. Display the resulting matrix.

Algorithm:
1. Parse the command line argument to get the size N.
2. Define two matrices of size N×N to store the input values.
3. Define a third matrix of size N×N to store the sum of the two input matrices.
4. For each element in the matrices:
● Read the values for the first matrix.

● Read the values for the second matrix.


Object Oriented Program Programming with java

● Compute the sum of corresponding elements from both matrices and store the result in the result
matrix.
5. Print the result matrix.

Explanation:
1. Command Line Argument Parsing:

● The program expects the matrix size N as a command line argument. If no argument is provided or
the argument is invalid, the program will ask the user to provide it correctly.
2. Reading Matrix Elements:

● The program uses a Scanner to read the matrix elements from the user.

● The user is prompted to input the values for two matrices, matrixA and matrixB, each with N×N
elements.
3. Matrix Addition:

● The program iterates over each element of the matrices, adds the corresponding elements, and stores
the result in resultMatrix.
4. Displaying the Result:

● Finally, the result matrix (sum of the two matrices) is displayed in a formatted way.

Notes:

● The size N must be the same for both matrices in order for the addition to work.

● The program assumes that the input is valid (no need for further validation).

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

implementation import java.io.*;

import java.util.*;
class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer>
stack)
{
Object Oriented Program Programming with java
for(int i = 0; i < 10; i++)
{
stack.push(i);
}
}
// Popping element from the top of the
stack static void
stack_pop(Stack<Integer> stack)
{
System.out.println("Pop
Operation:"); for(int i = 0; i < 10;
i++)
{
Integer y = (Integer)
stack.pop();
System.out.println(y);
}
}
// Displaying element on the top of the
stack static void
stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " +
element);
}
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer)
stack.search(element); if(pos == -1)
System.out.println("Element not
found"); else
System.out.println("Element is found at position: " + pos);
}
public static void main (String[] args)
{
Stack<Integer> stack = new
Stack<Integer>(); stack_push(stack);

stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
Output
Object Oriented Program Programming with java

Here is an algorithm to perform basic stack operations like push, pop, peek, and is
Empty:Definitions
● A stack is a Last-In-First-Out (LIFO) data structure.

● Operations:
1. Push: Add an element to the top of the stack.
2. Pop: Remove and return the top element.
3. Peek: Return the top element without removing it.
4. isEmpty: Check if the stack is empty.

Algorithm
Initialize Stack

1. Create a stack S as an empty list or array.


2. Define a top pointer initialized to -1.

Push Operation

1. Input: element
2. Increment the top pointer: top = top + 1
3. Add element at position top in S: S[top] = element

Explanation:
In Java, a stack is a data structure that follows the Last In, First Out (LIFO) principle, meaning the last
element added to the stack is the first one to be removed. Java provides a built-in Stack class in the
java.util package to perform stack operations. Below are common stack operations and examples of how to
use them:
Object Oriented Program Programming with java
1. Creating a Stack

You need to import the Stack class to use it:

java
Copy code
import java.util.Stack;

public class Main {


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

2. Basic Operations

1. Push (Add an element to the stack)

● Adds an element to the top of the stack.

java
Copy code
stack.push(10); // Adds 10 to the stack
stack.push(20); // Adds 20 to the stack

2. Pop (Remove the top element)

● Removes and returns the top element of the stack.


● Throws EmptyStackException if the stack is empty.

java
Copy code
int topElement = stack.pop(); // Removes and returns the top element (20)

3. Peek (View the top element without removing it)

● Returns the top element without removing it.


● Throws EmptyStackException if the stack is empty.

java
Copy code
int topElement = stack.peek(); // Returns the top element (10) without removing it

4. Check if the stack is empty

● Returns true if the stack is empty, otherwise false.

SYSTEM REQUIREMENTS:
Object Oriented Program Programming with java
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Object Oriented Program Programming with java

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.
import
java.io.*;
import
java.util.*;
public class
Employee
{ private int id;
private String
name; private
double salary;
// Constructor
public Employee(int id, String name, double
salary) { this.id = id;
this.name =
name;
this.salary =
salary;
}
// Getter
methods
public int
getId() {
return id;
}
public String
getName() { return
name;
}
public double
getSalary() { return
salary;
}
// Method to raise salary by a given
percentage public void raiseSalary(double
percent) {
if (percent > 0) {
double increaseAmount = salary * (percent /
100); salary += increaseAmount;
System.out.println(name + "'s salary has been increased by " + percent + "%. New salary: $" + salary);
} else {
Object Oriented Program Programming with java
System.out.println("Invalid percentage. Salary remains unchanged.");
}
}
public static void main(String[] args) {
// Create an Employee object
Employee employee1 = new Employee(1, "John Doe", 50000.0);
// Display initial employee information
System.out.println("Initial Employee Information:");
System.out.println("ID: " + employee1.getId());
System.out.println("Name: " +
employee1.getName()); System.out.println("Salary:
$" + employee1.getSalary());
// Raise the salary by 10%
employee1.raiseSalary(10);
// Display updated employee information

System.out.println("\nUpdated Employee
Information:"); System.out.println("ID: " +
employee1.getId()); System.out.println("Name: " +
employee1.getName()); System.out.println("Salary:
$" + employee1.getSalary());
}
}
Output :

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
Object Oriented Program Programming with java
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Algorithm:
1. Define the Employee class:

● Attributes:

● id: Store the employee's unique ID.

● name: Store the employee's name.

● salary: Store the employee's current salary.


2. Define the constructor (__init__):

● Initialize the attributes (id, name, salary) when a new employee object is created.
Object Oriented Program Programming with java
3. Define the raiseSalary method:

● This method will take a percent argument.

● The salary will be increased by the percentage provided.


4. Define the __str__ method (optional):

● This method will return a string representation of the employee object to display the employee's
details.
5. Create a main method (or test script):

● Create instances of the Employee class.

● Demonstrate the functionality of the raiseSalary method.

● Display the employee's details before and after the raise.

Explanation:

In this task, you're asked to design a class called Employee, which models an employee with three key
attributes: ID, name, and salary. The class will also have a method raiseSalary(percent) that increases
the salary of an employee by a given percentage. Additionally, a main method is required to demonstrate how
this class works.
Here’s a breakdown of what you need to do:

1. Attributes:

● ID: This could be an integer representing the unique ID for each employee.

● Name: A string representing the employee's name.

● Salary: A floating-point number representing the employee's salary.

2. Methods:

● raiseSalary(percent): This method takes a percentage as an argument, calculates the raise based on the
current salary, and then updates the salary. The formula for increasing the salary by a percentage is:
salary salarynew salary=current salary×(1+100percent)
● Constructor: A constructor (__init__ in Python) to initialize the attributes (ID, name, and salary).
Object Oriented Program Programming with java

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.
import
java.io.*;
import
java.util.*;
class MyPoint
Object Oriented Program Programming with java
{
private
int x;
private
int y;
// Default
constructor
public MyPoint()
{
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int
y) {
this.x
= x;
this.y
= y;
}
// 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() {
int[] coordinates = {x,
y}; return
coordinates;
}
// Method to return a string description of the
instance @Override
public String toString() {
return "(" + x + ", " + y + ")";
}
// Method to calculate distance to another point with given
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);
}
// Overloaded method to calculate distance to another MyPoint
instance public double distance(MyPoint another) {
return distance(another.x, another.y);
}
// Overloaded method to calculate distance to the origin
Object Oriented Program Programming with java
(0,0) public double distance() {
return distance(0, 0);
}
}
public class TestMyPoint {
public static void main(String[] args) {
// Create MyPoint objects
MyPoint point1 = new
MyPoint();
MyPoint point2 = new MyPoint(3, 4);
// Test setXY and getXY
methods point1.setXY(5, 6);
int[] coordinates = point1.getXY();
System.out.println("Point1 coordinates: (" + coordinates[0] + ", " + coordinates[1] + ")");
// Test toString method
System.out.println("Point2 coordinates: " + point2);
// Test distance methods
System.out.println("Distance between Point1 and (1, 1): " + point1.distance(1, 1));
System.out.println("Distance between Point1 and Point2: " +
point1.distance(point2)); System.out.println("Distance between Point2 and the
origin: " + point2.distance());
}
}

Output :
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display


● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Algorithm:
python
Copy code
class Stack:
def __init__(self):
self.stack = [] # Initialize the stack as an empty list

def is_empty(self):
Object Oriented Program Programming with java
"""
Returns True if the stack is empty, else False.
"""
return len(self.stack) == 0

def push(self, item):


"""
Adds an item to the top of the stack.
"""
self.stack.append(item)

def pop(self):
"""
Removes and returns the item from the top of the stack.
Raises IndexError if the stack is empty.
"""
if self.is_empty():
raise IndexError("pop from empty stack")
return self.stack.pop()

def peek(self):
"""
Returns the item at the top of the stack without removing it.
Raises IndexError if the stack is empty.
"""
if self.is_empty():
raise IndexError("peek from empty stack")
return self.stack[-1]

def size(self):
"""
Returns the number of items in the stack.
"""
return len(self.stack)

def __str__(self):
"""
Returns a string representation of the stack.
"""
return f"Stack(top -> {', '.join(map(str, self.stack[::-1]))})"

Explanation:
1. __init__(): Initializes an empty list to represent the stack.
2. is_empty(): Checks if the stack is empty.
3. push(item): Adds an item to the top of the stack.
4. pop(): Removes and returns the item from the top of the stack. Raises an error if the stack is empty.
5. peek(): Returns the top item without removing it. Raises an error if the stack is empty.
6. size(): Returns the number of items in the stack.
7. __str__(): Provides a string representation of the stack, with the top of the stack listed first.

Example Usage:
python
Copy code
# Create a stack
s = Stack()

# Push items onto the stack


Object Oriented Program Programming with java
s.push(10)
s.push(20)
s.push(30)

# Print the stack


print(s) # Output: Stack(top -> 30, 20, 10)

# Peek the top item


print(s.peek()) # Output: 30

# Pop an item from the stack


print(s.pop()) # Output: 30

# Check if the stack is empty


print(s.is_empty()) # Output: False

# Get the size of the stack


print(s.size()) # Output: 2

This implementation ensures efficient stack operations with O(1) complexity for each method.

4o mini

5. Develop a JAVA program to create a class named shape. Create three sub classes
Object Oriented Program Programming with java
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.
import
java.io.*;
import
java.util.*;
class Shape {
public void draw()
{ System.out.println("Drawing a
shape");
}
public void erase()
{ System.out.println("Erasing a
shape");
}
}
class Circle extends
Shape { @Override
public void draw()
{ System.out.println("Drawing a
circle");
}
@Override
public void erase()
{ System.out.println("Erasing a
circle");
}
}
class Triangle extends
Shape { @Override
public void draw()
{ System.out.println("Drawing a
triangle");
}
@Override
public void erase()
{ System.out.println("Erasing a
triangle");
}
}
class Square extends
Shape { @Override
public void draw()
{ System.out.println("Drawing a
square");
}
@Override
public void erase()
{ System.out.println("Erasing a
Object Oriented Program Programming with java
square");
}
}
public class ShapeDemo {
public static void main(String[] args) {

// Polymorphism: Create an array of Shape


objects Shape[] shapes = new Shape[3];
shapes[0] = new
Circle(); shapes[1] =
new Triangle();
shapes[2] = new
Square();
// Demonstrate polymorphic
behavior for (Shape shape :
shapes) { shape.draw();
shape.erase();
System.out.println(); // Separate each shape's output
}
}
}

Output :

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution
Object Oriented Program Programming with java
2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Algorithm:
1. Define a base class Shape:

● Declare the methods draw() and erase().

● These methods will be abstract because the actual implementation will be provided by the
subclasses.
2. Create subclasses Circle, Triangle, and Square:

● Each subclass should extend the Shape class.

● Override the draw() and erase() methods in each subclass with their specific implementations.
3. Use polymorphism:
Object Oriented Program Programming with java
● Create an array or list of Shape references in the main method.

● Add objects of Circle, Triangle, and Square to this array/list.

● Use the draw() and erase() methods on the Shape references, which will invoke the
overridden methods of the respective subclasses.

Explanation:
1. Shape Class (Super Class)

The Shape class is the base class for all the shapes. It contains the draw() and erase() methods, but they are
just placeholders (abstract methods in this case). We don't implement these methods here because each subclass
will provide its own implementation.

java
Copy code
abstract class Shape {
// Abstract method to draw the shape
public abstract void draw();

// Abstract method to erase the shape


public abstract void erase();
}

● abstract keyword means the class cannot be instantiated directly and must be subclassed.

● The draw() and erase() methods are abstract and don't have bodies because each shape has its own
way of drawing and erasing.

2. Circle Class (Subclass of Shape)

The Circle class extends Shape and provides implementations for the draw() and erase() methods.

java
Copy code
class Circle extends Shape {
// Draw method specific to Circle
public void draw() {
System.out.println("Drawing a Circle");
}

// Erase method specific to Circle


public void erase() {
System.out.println("Erasing the Circle");
}
}

● Circle provides its own draw() and erase() methods.

● The draw() method prints a message to indicate drawing a circle, and the erase() method does the
same for erasing the circle.

3. Triangle Class (Subclass of Shape)


Object Oriented Program Programming with java
The Triangle class also extends Shape and provides implementations for the draw() and erase() methods.

java
Copy code
class Triangle extends Shape {
// Draw method specific to Triangle
public void draw() {
System.out.println("Drawing a Triangle");
}

// Erase method specific to Triangle


public void erase() {
System.out.println("Erasing the Triangle");
}
}

● Triangle implements its own version of the draw() and erase() methods.

4. Square Class (Subclass of Shape)

The Square class, like the other subclasses, extends Shape and implements the draw() and erase()
methods.

java
Copy code
class Square extends Shape {
// Draw method specific to Square
public void draw() {
System.out.println("Drawing a Square");
}

// Erase method specific to Square


public void erase() {
System.out.println("Erasing the Square");
}
}

● Square provides its own definitions for the draw() and erase() methods.

5. Main Program (Demonstrating Polymorphism)

In the main program, polymorphism is demonstrated by creating references of type Shape but instantiating objects
of the subclasses (Circle, Triangle, and Square). This is where the concept of polymorphism (method
overriding) comes into play, as the draw() and erase() methods will be called based on the actual object type
(not the reference type).

java
Copy code
public class Main {
public static void main(String[] args) {
// Creating objects of the derived classes
Shape circle = new Circle();
Shape triangle = new Triangle();
Shape square = new Square();

// Polymorphism in action: the correct method is called based on the object type
Object Oriented Program Programming with java
circle.draw(); // Outputs: Drawing a Circle
circle.erase(); // Outputs: Erasing the Circle

triangle.draw(); // Outputs: Drawing a Triangle


triangle.erase();// Outputs: Erasing the Triangle

square.draw(); // Outputs: Drawing a Square


square.erase(); // Outputs: Erasing the Square
}
}

● Polymorphism is demonstrated by calling the draw() and erase() methods on references of type
Shape, but the actual methods executed are from the Circle, Triangle, and Square classes,
depending on the object assigned to the reference.
● The actual method that gets called at runtime is determined by the type of object that the reference points to.
This is the key concept of method overriding in Java.

Key Concepts Demonstrated

● Inheritance: The Circle, Triangle, and Square classes inherit from the Shape class.

● Method Overriding: The draw() and erase() methods are overridden in each subclass.

● Polymorphism: The ability to call the same method (draw() and erase()) on different types of objects
and have the correct version of the method executed based on the actual object type.

In summary, this program uses inheritance, method overriding, and polymorphism to create a hierarchy of shapes
and demonstrate how Java resolves which method to call at runtime based on the actual object type.
Object Oriented Program Programming with java

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.
import java.io.*;
import java.util.*;
abstract class
Shape {
// Abstract methods to calculate area and
perimeter public abstract double
calculateArea();
public abstract double calculatePerimeter();
}
class Circle extends
Shape { private double
radius;
// Constructor for Circle
public Circle(double
radius) { this.radius =
radius;
}
// Implementation of abstract
methods @Override
public double
calculateArea() { return
Math.PI * radius * radius;
}
@Override
public double
calculatePerimeter() { return 2 *
Math.PI * radius;
}
}
class Triangle extends Shape
{ private double side1, side2,
side3;
// Constructor for Triangle
Object Oriented Program Programming with java
public Triangle(double side1, double side2, double
side3) { this.side1 = side1;
this.side2 =
side2;
this.side3 =
side3;
}
// Implementation of abstract
methods @Override
public double calculateArea() {
// Heron's formula for area of a
triangle double s = (side1 + side2 +
side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double
calculatePerimeter() { return
side1 + side2 + side3;
}
}

public class ShapeDemo {


public static void main(String[] args) {
// Creating objects of Circle and
Triangle Circle circle = new
Circle(5);
Triangle triangle = new Triangle(3, 4, 5);
// Displaying area and perimeter for Circle
System.out.println("Circle - Area: " + circle.calculateArea() + ", Perimeter: " + circle.calculatePerimeter());
// Displaying area and perimeter for Triangle
System.out.println("Triangle - Area: " + triangle.calculateArea() + ", Perimeter:
" + triangle.calculatePerimeter());
}
}

Output :
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Here's an algorithm to implement the Java program based on your description:


Algorithm:
1. Define the abstract class Shape:

● Declare the abstract methods calculateArea() and calculatePerimeter().


Object Oriented Program Programming with java
2. Create the Circle subclass:

● Declare a radius attribute to store the radius of the circle.

● Implement the calculateArea() method to compute the area of the circle using the formula:
Area=π×r2
● Implement the calculatePerimeter() method to compute the perimeter of the circle using the
formula: Perimeter=2×π×r
3. Create the Triangle subclass:

● Declare attributes for the three sides of the triangle (e.g., side1, side2, side3).

● Implement the calculateArea()


method using Heron's formula: Area=s×(sa)×(sb)×(sc) where s=2a+b

● Implement the calculatePerimeter() method by summing the lengths of the sides:


Perimeter=a+b+c
4. Test the program in the main method:

● Create instances of Circle and Triangle and call the calculateArea() and
calculatePerimeter() methods to display the results.

Explanation:
Here’s an explanation for the Java program that involves creating an abstract
class Shape with abstract methods calculateArea() and calculatePerimeter(),
and creating subclasses Circle and Triangle that extend the Shape class and
implement these methods:
1. Abstract Class Shape

● An abstract class in Java is a class that cannot be instantiated directly. It is used to define a common base
for subclasses.
● The Shape class contains abstract methods calculateArea() and calculatePerimeter().
These methods have no implementation in the abstract class but must be implemented by any subclass.
● The Shape class might also have common attributes, but its main purpose here is to act as a blueprint for
other shapes like Circle and Triangle.

2. Abstract Methods

● calculateArea(): This method will be implemented by each subclass to calculate the area of the
respective shape.
● calculatePerimeter(): This method will be implemented by each subclass to calculate the perimeter
of the respective shape.

3. Subclasses: Circle and Triangle


Object Oriented Program Programming with java
● Circle: This subclass extends Shape. It needs to implement both the calculateArea() and
calculatePerimeter() methods. The area of a circle is calculated by the formula π * radius^2,
and the perimeter (or circumference) is calculated by 2 * π * radius.
● Triangle: This subclass also extends Shape. The area of a triangle is calculated by 0.5 * base *
height, and the perimeter is the sum of its three sides.

4. Why Use Abstract Classes?

● Abstract classes allow you to define methods that must be implemented by subclasses, ensuring that all
shapes will have a way to calculate their area and perimeter, regardless of the specific type of 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
import
java.io.*;
import
java.util.*;
// Resizable
interface
interface
Resizable {
void resizeWidth(int
width); void
resizeHeight(int height);
}
// Rectangle class implementing Resizable
interface class Rectangle implements Resizable
{
private int
width; private
int height;
// Constructor for Rectangle
Object Oriented Program Programming with java
public Rectangle(int width, int
height) { this.width = width;
this.height = height;
}

// Implementation of resize methods from Resizable


interface @Override
public void resizeWidth(int
width) { this.width = width;
}
@Override
public void resizeHeight(int
height) { this.height = height;
}
// Method to display rectangle
information public void display() {
System.out.println("Rectangle - Width: " + width + ", Height: " + height);
}
}
public class ResizableDemo {
public static void main(String[] args) {
// Create a Rectangle object
Rectangle rectangle = new Rectangle(10, 5);
// Display original rectangle
information
System.out.println("Original
Rectangle:"); rectangle.display();
// Resize the rectangle
rectangle.resizeWidth(15);
rectangle.resizeHeight(8);
// Display resized rectangle information
System.out.println("\nResized Rectangle:");
rectangle.display();
}
}

Output :
Object Oriented Program Programming with java

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display


● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

To develop a Java program that defines an interface Resizable with methods for resizing the width and
height of an object, and then creates a Rectangle class that implements the interface, you can follow
these steps:
Algorithm
1. Define the Resizable interface:
Object Oriented Program Programming with java
●The interface will have two methods: resizeWidth(int width) and resizeHeight(int
height).
2. Create the Rectangle class:

● The Rectangle class should have two properties: width and height.
●It should implement the Resizable interface by providing implementations for the
resizeWidth and resizeHeight methods.
3. Create a constructor and methods in the Rectangle class:

● The constructor will initialize the width and height.


● Implement the methods resizeWidth and resizeHeight to modify the dimensions of the
rectangle.
4. Test the functionality in a main method:

● Create an instance of Rectangle, display its initial size, resize it using the methods from
Resizable, and display the updated size.

Explanation:
1. Resizable Interface:

The Resizable interface defines two methods: resizeWidth(int width) and



resizeHeight(int height). These methods allow an object to change its width and height.
2. Rectangle Class:

● The Rectangle class implements the Resizable interface, which requires it to provide
implementations for resizeWidth and resizeHeight.
● It also has a constructor to initialize the width and height of the rectangle and a `display Dimension

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.
import
java.io.*;
import
java.util.*;
class
OuterClass {
// Outer class display
function public void
display() {
System.out.println("OuterClass display function");
}
// Inner class
class
Object Oriented Program Programming with java
InnerClass {
// Inner class display
function public void
display() {
System.out.println("InnerClass display function");
}
}
}
public class MainClass {
public static void main(String[] args) {
// Create an instance of OuterClass
OuterClass outerObject = new
OuterClass();
// Call the display function of the outer
class outerObject.display();
// Create an instance of InnerClass (nested class)
OuterClass.InnerClass innerObject = outerObject.new
InnerClass();
// Call the display function of the inner
class innerObject.display();
}}

Output:
arduino
Copy code
This is the display method of the Outer class.
This is the display method of the Inner class.

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution
Object Oriented Program Programming with java
2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Here is the algorithm for creating a Java program with an outer class containing an inner class, where both
classes have a display function:
Algorithm:
1. Define the Outer Class:

● Create a public outer class (e.g., Outer).


●Inside the outer class, define a method display() that prints a message indicating it belongs to the
outer class.
2. Define the Inner Class:

● Inside the outer class, define a public static inner class (e.g., Inner).
Inside the inner class, define a method display() that prints a message indicating it belongs to the

inner class.
3. Main Class (Main Method):
Object Oriented Program Programming with java
● In the main() method, create an instance of the outer class.
● Call the display() method of the outer class.
● Create an instance of the inner class and call its display() method.

Explanation:

● Outer Class (Outer): Contains a method display() which prints a message.


● Inner Class (Inner): Defined inside the outer class, it also contains its own display() method.
● Main Method: An object of the outer class is created, and its display() method is called. Then, an
object of the inner class is created using the outer class object, and the inner class's display() method is
called.

9. Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
import
java.io.*;
import
java.util.*;
// Custom exception class
class DivisionByZeroException extends Exception
{ public DivisionByZeroException(String
message) {
super(message);
}
}
public class CustomExceptionDemo
{ public static void main(String[]
Object Oriented Program Programming with java
args) {
try {
// Call a method that may throw the custom
exception divideNumbers(10, 0);
} catch (DivisionByZeroException e) {
// Catch the custom exception and handle it
System.out.println("Error: " + e.getMessage());
} finally {
// Code in the finally block will always be executed, whether an exception occurs or
not System.out.println("Finally block executed");
}
}
// Method that may throw the custom exception
private static void divideNumbers(int numerator, int denominator) throws
DivisionByZeroException { try {
// Attempt to perform division
int result = numerator / denominator;
// Display the result if successful
System.out.println("Result of division: " +
result);
} catch (ArithmeticException e) {
// Catch the ArithmeticException (division by zero) and throw a custom
exception throw new DivisionByZeroException("Cannot divide by zero");
}
}
}

Output :ERROR:Cannot divide by zero


Finally block executed

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
Object Oriented Program Programming with java
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Here's an algorithm to create a Java program that raises a custom exception (user-defined exception) for a division by zero
scenario using try, catch, throw, and finally blocks.

Algorithm:
1. Define a Custom Exception Class:

Create a custom exception class DivisionByZeroException that extends the Exception



class.
● This class should have a constructor that takes a string message to describe the exception.
2. Create the Main Class:

● In the main class, define a method divide that accepts two parameters (dividend and divisor).
● Inside the divide method, check if the divisor is zero.
If true, throw the custom DivisionByZeroException using throw and provide an

appropriate message.
● If the divisor is not zero, perform the division and return the result.
3. Use try-catch-finally Block:

● In the main method, call the divide method inside a try block.
● Catch the DivisionByZeroException using a catch block and display the error message.
● Use a finally block to print a message indicating that the program execution has completed (for
resource cleanup or final statements).
Object Oriented Program Programming with java
Explanation:
1. DivisionByZeroException Class: This is a user-defined exception that inherits from Exception. It
accepts a custom error message when the exception is thrown.
2. Divide Method: The method checks if the divisor is zero and throws the custom exception if it is.
Otherwise, it performs the division and returns the result.
3. Main Method:
● A try block calls the divide method.

● If the divisor is zero, the DivisionByZeroException is thrown and caught in the catch
block, which displays the error message.
● The finally block always runs, printing a message indicating the completion of program
execution.
Object Oriented Program Programming with java
10. Develop a JAVA program to create a package named mypack and import &
implement it in a suitable class.

1. Create a package named mypack with a class inside it:


// File:
mypack/MyPackageClass.java
package mypack;
public class MyPackageClass
{ public void
displayMessage() {
System.out.println("This is a message from MyPackageClass in the mypack package.");
}
}
2. Create a class outside the package that imports and uses the class from the mypack package:
// File: MyMainClass.java
import
mypack.MyPackageClass;
public class MyMainClass {
public static void main(String[] args) {
// Create an object of MyPackageClass and call the displayMessage
method MyPackageClass myPackageObject = new MyPackageClass();
myPackageObject.displayMessage();
}
}
3. Directory Structure:
- myprogram/
- mypack/
- MyPackageClass.java

Output
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display


● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Here’s a step-by-step algorithm to create a Java program that:


1. Creates a package named mypack.
2. Defines a class in the package with some methods.
3. Imports the package into another class and uses the methods.
Object Oriented Program Programming with java
Algorithm:
1. Step 1: Create a new package mypack.

● In Java, packages are typically stored in directories, so we will create a directory named mypack to
hold our classes.
2. Step 2: Create a class MyClass inside the mypack package.

● In this class, define some methods that we can later use in another class.
3. Step 3: Create another class MainClass outside the mypack package.

● Import the mypack package using the import statement.

● Create an instance of MyClass and call its methods.

Explanation:
1. Step 1: Save MyClass.java inside a folder named mypack.

2. Step 2: Save MainClass.java in the parent directory (outside mypack).

3. Step 3: Open a terminal/command prompt and navigate to the directory where MainClass.java is
located.

4. Step 4: Compile the package and the class:


Object Oriented Program Programming with java

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).
class MyRunnable implements
Runnable { private String
threadName;
// Constructor to initialize the thread
name public MyRunnable(String
name) {
this.threadName = name;
}
// Run method to be executed when the thread
starts public void run() {
try {
for (int i = 0; i < 5; i++)
{ System.out.println(threadName + ": Count
" + i);
// Suspend the thread for 500
milliseconds Thread.sleep(500);
}
} catch (InterruptedException e)
{ System.out.println(threadName + "
interrupted.");
}
System.out.println(threadName + "
exiting."); } } public class RunnableThreadExample
{
public static void main(String[] args) {
// Create two threads using the MyRunnable class
Thread thread1 = new Thread(new MyRunnable("Thread
1")); Thread thread2 = new Thread(new
MyRunnable("Thread 2"));
// Start the
threads
thread1.start();
thread2.start();
}}

Outp
ut ;
Object Oriented Program Programming with java
Object Oriented Program Programming with java
SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display


● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.
Object Oriented Program Programming with java
Algorithm:
To create threads using the Runnable interface in Java, you'll need to follow these steps:
1. Implement the Runnable Interface: Create a class that implements Runnable and override the run()
method. Inside the run() method, you will use Thread.sleep(500) to suspend the thread for 500
milliseconds.

2. Create a Thread Object: In the main method or another part of your program, instantiate the Runnable
class and pass it to a Thread object.

3. Start the Thread: Use the start() method of the Thread object to begin the execution of the thread.

Here is a simple implementation of this algorithm:

Explanation:
1. MyRunnable Class: Implements the Runnable interface and overrides the run() method. Inside
run(), Thread.sleep(500) pauses the thread for 500 milliseconds.

2. ThreadExample Class: Creates three Thread objects, each associated with a Runnable instance
(myRunnable). The start() method is called on each Thread to begin execution, which will execute
the run() method of the Runnable interface.

This approach demonstrates how to create and start threads using the Runnable interface in Java, and how to
suspend the execution of a thread for a specific amount of time using Thread.sleep().
Object Oriented Program Programming with java

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 the main thread and created child thread are executed
concurrently.
class MyThread extends Thread {
// Constructor calling base class constructor using
super public MyThread(String threadName) {
super(threadName);
// Start the thread when the constructor is
called start();
}
// Run method to be executed when the thread
starts public void run() {
for (int i = 0; i < 5; i++)
{ System.out.println(Thread.currentThread().getName() + ": Count
" + i); try {
// Sleep for 500
milliseconds
Thread.sleep(500);
} catch (InterruptedException e)
{ System.out.println(Thread.currentThread().getName() + "
interrupted.");
}
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}
}
public class MyThreadExample {
public static void main(String[] args) {
// Main thread execution
System.out.println("Main thread
started.");

// Create an instance of MyThread (child thread)


MyThread myThread = new MyThread("Child
Thread");
// Continue main thread
execution for (int i = 0; i < 5;
i++) {
System.out.println("Main Thread: Count "
+ i); try {
// Sleep for 300
milliseconds
Thread.sleep(300);
} catch (InterruptedException e)
{ System.out.println("Main Thread
interrupted.");
}
}
Object Oriented Program Programming with java
// Main thread exiting
System.out.println("Main thread
exiting.");
}
}

Output :

SYSTEM REQUIREMENTS:
To run Java programs using Eclipse, your system should meet the following minimum requirements:

1. Operating System

● Windows: Windows 10 or later (64-bit)


● macOS: macOS 10.13 (High Sierra) or later
● Linux: Any modern 64-bit Linux distribution

2. Java Development Kit (JDK)

● JDK Version: Eclipse requires at least Java 8 to run. For new projects, it's recommended to use a JDK 11
or higher (depending on your project needs).
○ JDK 11 is a long-term support (LTS) version.
○ JDK 17 is also widely supported and preferred for new projects.

3. Eclipse IDE

● Eclipse IDE for Java Developers or Eclipse IDE for Java EE Developers.
● Download the appropriate version from the official Eclipse website:
○ Eclipse IDE for Java Developers: Ideal for basic Java development.
○ Eclipse IDE for Java EE Developers: Recommended for enterprise applications and includes
additional tools for web development (like support for Java EE, Maven, and more).

4. Memory and Storage

● RAM: Minimum 4 GB (8 GB or more recommended for optimal performance)


Object Oriented Program Programming with java
● Storage: Minimum 1 GB of free space for the Eclipse IDE installation, with additional space required for
projects and libraries.

5. Graphics and Display

● Graphics: The system should support a display with at least 1024x768 resolution.

6. Additional Tools (Optional)

● Maven/Gradle: For managing project dependencies (if used in your project).


● Git: If you're using version control, Git can be installed or configured within Eclipse.

Once these basic requirements are met, you can use Eclipse for Java development efficiently. Additionally, keep
your Java Runtime Environment (JRE) and Eclipse IDE updated for security and performance enhancements.

Algorithm:
To create a class MyThread that extends the Thread class in Python, uses super() to call the base class
constructor, and starts the thread, you can follow these steps:
1. Create a class MyThread that inherits from Thread.
2. Define the __init__ method and call the parent class constructor using super().
3. Override the run method where the code for the child thread will be executed.
4. Start the thread by calling the start method in the constructor.

Explanation:
1. MyThread class: Inherits from threading.Thread and overrides the __init__ and run methods.

● The __init__ method uses super().__init__() to initialize the parent class (Thread),
allowing you to start the thread later.
● The run method contains the logic that the thread will execute when started. It prints messages in a
loop with a delay.
2. thread1.start() and thread2.start(): This starts the threads, which triggers the run method of
each thread to execute concurrently with the main thread.

3. join(): The join() method ensures that the main thread waits for both child threads to complete before
exiting the program.

Output:
The program will output messages from both the main thread and the child threads running concurrently. The exact
order of the output may vary each time you run the program due to the concurrent execution of threads.
Finally block executed
Object Oriented Program Programming with java

Appendix
CREATE PROJECT:
Object Oriented Program Programming with java

A Eclipse tools
A new project is created and displayed as a folder. Open the com.vogella.eclipse.ide.first folder and explore the content of
this folder.

In this tutorial the project is typically named the same as the top-level Java
package in the project. This makes is easier to find a project related to a piece of
code.

Create package
A good naming convention is to use the same name for the top level package and the
project. For example, if you name your project com.example.javaproject you should also
use com.example.javaproject as the top-level package name.

Create the com.vogella.eclipse.ide.first package by seleting the src folder, right-click on it and select New Package.

Press the Finish button.


Object Oriented Program Programming with java
Finish

Create Java class


Right-click on your package and select New Class to create a Java class.

Enter MyFirstClass as the class name and select the public static void main (String[] args) checkbox.

Press the button.


Object Oriented Program Programming with java
This creates a new file and opens the Java editor. Change the class based on the following listing.

package com.vogella.eclipse.ide.first;

public class MyFirstClass {


public static void main(String[]
args) { System.out.println("Hello
Eclipse!");
}

You could also directly create new packages via this dialog. If you enter a new package in this dialog, it is created automatically.

Run your application code from the IDE


Now run your code. Either right-click on your Java class in the Package Explorer or right-click in the Java class and select
Run- as Java application.

Eclipse will run your Java program. You should see the output in the Console view.

Congratulations! You created your first Java project, a package, a Java class and you ran this program inside Eclipse.
Object Oriented Program Programming with java
Appendix B

SAMPLE PROGRAMS ON DATA STRUCTURES

Program 1
Declare a program to initialize, then that variable will be reinitialized each time the block in which
it is declared is entered.
// Demonstrate lifetime of a
variable. class LifeTime {
public static void main(String
args[]) { int x; for(x = 0; x < 3; x+
+) {
int y = -1; // y is initialized each time block is
entered System.out.println("y is: " + y); // this
always prints -1 y = 100;
System.out.println("y is now: " + y);
}
}
}

The output generated by this program is shown here: y


is: -1 y is now: 100
y is: -1
y is now:
100 y is: -
1
y is now: 100

Program2
Demonstrate program demonstrates some type conversions that require casts:
// Demonstrate
casts. class
Conversion {
public static void main(String
args[]) { byte b;
int i = 257;
double d = 323.142; System.out.println("\
nConversion of int to byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to
int."); i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to
byte."); b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Object Oriented Program Programming with java

This program generates the following output:

Conversion of int to
byte. i and b 257 1
Conversion of double to
int. d and i 323.142 323
Conversion of double to
byte. d and b 323.142 67

Program3
Demonstrate program numbers each element in the array from left to right, top to bottom, and then displays
these values:
// Demonstrate a two-dimensional
array. class TwoDArray {
public static void main(String
args[]) { int twoD[][]= new int[4]
[5];
int i, j, k = 0;
for(i=0; i<4;
i++) for(j=0;
j<5; j++)
{ twoD[i][j] =
k; k++;

for(i=0; i<4;
i++) { for(j=0;
j<5; j++)
System.out.print(twoD[i][j] +
" "); System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19

Program4
Demonstrate a sample program that shows several op= assignments in action:
// Demonstrate several assignment
operators. class OpEquals {
public static void main(String
args[]) { int a = 1;
int b
= 2;
int c
= 3;
a +=
5;
b *= 4;
c += a
* b; c
%= 6;
System.out.println("a = "
Object Oriented Program Programming with java
+ a);
System.out.println("b = "
+ b);
System.out.println("c = "
+ c);
Object Oriented Program Programming with java
}
}
The output of this program is shown here:
a=6
b=8
c=3

Program 5
Demonstrate a program that uses an if-else-if ladder to determine which season a particular
month is in.
// Demonstrate if-else-if
statements. class IfElse {
public static void main(String
args[]) { int month = 4; // April
String season;
if(month == 12 || month == 1 || month
== 2) season = "Winter";
else if(month == 3 || month == 4 || month
== 5) season = "Spring";
else if(month == 6 || month == 7 || month
== 8) season = "Summer";
else if(month == 9 || month == 10 || month
== 11) season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}

Here is the output produced by the


program: April is in the Spring.
Object Oriented Program Programming with java
VIVA QUESTIONS

1. What is OOPs?
It is a programming paradigm that is used to develop software applications by creating objects that interact with
each other.

2. What are the key principles of OOPs?


It is one of the most asked interview questions on OOPs concepts. You must know that there are four principles
of OOP using which developers can write code more efficiently and maintain it with ease. a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction

3. What is a class in OOPs?


It is a blueprint or a template for constructing objects. It is used to define a set of properties and methods that will
be present in an object belonging to that class.

4. What is an object in OOPs?


An object is an instance of a class. It is a concrete entity that can be created based on a class blueprint.

5. What is inheritance in OOPs?


This is among the top OOPs questions for the interview. Inheritance is the process of creating a new class (called
the subclass or child class) from an existing class (called the superclass or parent class).

6. What is encapsulation in OOPs?


Encapsulation is the concept of hiding the implementation details of a class from its users, and providing a
public interface or API (Application Programming Interface) for interacting with the class.

7. What is an abstraction in OOPs?


It is the process used to define a simplified interface or model that represents the essential features of an object,
without including unnecessary details or implementation specifics.

8. What is polymorphism in OOPs?


Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different
classes to be treated as if they are objects of a common superclass or interface.

9. What is method overloading? Explain with an example.


It is a form of static polymorphism that allows multiple methods to have the same name but with different
parameters or argument types Example of method overloading in OOPs For example, consider a class called
“Math” that contains two overloaded methods called “add”.

The first method takes two integers as arguments and returns their sum, while the second method takes two
doubles as arguments and returns their sum.

When we call the “add” method with two integers, the first method is called, and when we call the “add”
method with two doubles, the second method is called.
Object Oriented Program Programming with java
10. What is method overriding? Explain with an example.
It is a form of dynamic polymorphism that allows a subclass to provide its own implementation of a method
that is already defined in its superclass

For example, consider a class hierarchy that includes a superclass called “Animal” and a subclass called “Dog”.
The Animal class may have a method called “speak” that returns a string, while the Dog subclass may override
the “speak” method to return “woof”. When we call the “speak” method on a Dog object, the overridden
method in the Dog class is called, and when we call the “speak” method on an Animal object, the original
method in the Animal class is called.

11. What is a constructor?


A constructor in OOP is a special method that is called when an object is created. Its main purpose is to
initialise the object’s state or data members with some initial values.

12. What are the different types of constructors?


There are two types of constructors:

a) Default constructor
This constructor is provided by Java if a class does not have any constructors explicitly defined. It takes no
parameters and initializes all the data members to their default values (e.g., null for object references, 0 for
integers, etc.).

b) Parameterized constructor
This constructor is defined by the programmer and takes one or more parameters. It initializes the data members
with the values passed as arguments.

13. What is a static method?


A static method in Java is a method that belongs to the class rather than to any instance of the class. This means
that you can call a static method without creating an instance of the class first. You can call it directly on the
class itself using the class name.

14. What is a static variable?


In Java, a static variable is a variable that belongs to the class rather than to any instance of the class. This
means that all instances of the class share the same static variable, and changes to the static variable by one
instance will be visible to all other instances.

15. What is a class in OOPs?


It is a blueprint or a template for constructing objects. It is used to define a set of properties and methods that
will be present in an object belonging to that class.

16. What is an object in OOPs?


An object is an instance of a class. It is a concrete entity that can be created based on a class blueprint.

When an object is created, it has its own unique set of properties and methods based on the definition of its
class. These properties and methods can be accessed and manipulated through the object’s public interface,
which consists of its public methods and properties.

17. What is encapsulation in OOPs?


Object Oriented Program Programming with java
Encapsulation is the concept of hiding the implementation details of a class from its users, and providing a
public interface or API (Application Programming Interface) for interacting with the class.

The idea behind encapsulation is to protect the internal state of an object from being modified directly by
external code, and to enforce the use of the public interface for any interactions with the object. This helps to
prevent errors and ensure that the object is used correctly.

18. What is an abstraction in OOPs?


It is the process used to define a simplified interface or model that represents the essential features of an object,
without including unnecessary details or implementation specifics.

19. What is polymorphism in OOPs?


Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different
classes to be treated as if they are objects of a common superclass or interface.

20. What is method overloading? Explain with an example.


It is a form of static polymorphism that allows multiple methods to have the same name but with different
parameters or argument types. Example of method overloading in OOPs

For example, consider a class called “Math” that contains two overloaded methods called “add”.

The first method takes two integers as arguments and returns their sum, while the second method takes two
doubles as arguments and returns their sum.

When we call the “add” method with two integers, the first method is called, and when we call the “add”
method with two doubles, the second method is called.

21. What is method overriding? Explain with an example.


It is a form of dynamic polymorphism that allows a subclass to provide its own implementation of a method
that is already defined in its superclass. Example of method overriding in OOPs

For example, consider a class hierarchy that includes a superclass called “Animal” and a subclass called “Dog”.
The Animal class may have a method called “speak” that returns a string, while the Dog subclass may override
the “speak” method to return “woof”.

When we call the “speak” method on a Dog object, the overridden method in the Dog class is called, and when
we call the “speak” method on an Animal object, the original method in the Animal class is called.

22. What is a constructor?


A constructor in OOP is a special method that is called when an object is created. Its main purpose is to initialise
the object’s state or data members with some initial values.

In Java, a constructor has the same name as the class and does not have a return type, not even void. It is called
implicitly when an object is created using the “new” keyword, and it can also be called explicitly like any other
method.

23. What are the different types of constructors?


There are two types of constructors:
Object Oriented Program Programming with java
a) Default constructor
This constructor is provided by Java if a class does not have any constructors explicitly defined. It takes no
parameters and initializes all the data members to their default values (e.g., null for object references, 0 for
integers, etc.).

b) Parameterized constructor
This constructor is defined by the programmer and takes one or more parameters. It initializes the data members
with the values passed as arguments.

24. What is a static method?


A static method in Java is a method that belongs to the class rather than to any instance of the class. This means
that you can call a static method without creating an instance of the class first. You can call it directly on the
class itself using the class name.

25. What is a static variable?


In Java, a static variable is a variable that belongs to the class rather than to any instance of the class. This
means that all instances of the class share the same static variable, and changes to the static variable by one
instance will be visible to all other instances.

26. What is the difference between an instance variable and a class variable?
In object-oriented programming, instance variables and class variables are two types of variables that can be
declared within a class. The main difference between them is that instance variables are associated with an
instance of a class, while class variables are associated with the class itself.

27. What is a package in Java?


In Java, a package is a mechanism for organising related classes and interfaces into a single unit. It provides a
way to group related classes and interfaces together in a logical manner, and also provides a way to control
access to the members of the classes and interfaces.

28. What are the four fundamental principles of OOPs?


The four fundamental principles of Object-Oriented Programming (OOPs) are:

● Encapsulation

● Inheritance

● Polymorphism

● Abstractio

29. What is the difference between abstraction and encapsulation?


Abstraction and Encapsulation are two important concepts in Object-Oriented Programming (OOPs). They are
often confused with each other as they both deal with hiding complexity, but they are different in nature.

30. What is the difference between inheritance and polymorphism?


Inheritance and Polymorphism are two important concepts in Object-Oriented Programming (OOPs). They are
often used together to create reusable and extensible code.

You might also like