Oops in java
Unit 2:-
1. Discuss the concept of static methods and variables in Java. How does the static keyword
affect the behavior of class members? Provide an example.
Answer:-
In Java, the keyword static is used to create class-level members.
Static variables and static methods belong to the class, not individual objects.
All objects share static variables, and static methods can be called without creating
an object.
Non-static members belong to objects, and each object has its own copy.
2. Box Example (Width, Height, Depth, Volume)
Member Type Example Description
Non-static width, height, Each box has its own dimensions. Changing one box
variable depth does not affect others.
Static variable material All boxes share the same material (common property).
Non-static Calculates volume of a specific box. Requires object to
volume()
method call.
Displays the shared material. Can be called without any
Static method displayMaterial()
object.
3. Combined Program Example
class Box {
double width; // Non-static variable
double height; // Non-static variable
double depth; // Non-static variable
static String material; // Static variable
// Constructor to initialize dimensions
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
// Non-static method to calculate volume
double volume() {
return width * height * depth;
// Static method to display shared material
static void displayMaterial() {
[Link]("Material of all boxes: " + material);
public class TestBox {
public static void main(String[] args) {
// Set static variable (shared by all boxes)
[Link] = "Cardboard";
// Create box objects with different dimensions
Box box1 = new Box(2, 3, 4);
Box box2 = new Box(5, 6, 7);
// Display volume of each box (non-static method)
[Link]("Volume of Box1: " + [Link]());
[Link]("Volume of Box2: " + [Link]());
// Display shared material using static method
[Link]();
4. Output
Volume of Box1: 24.0
Volume of Box2: 210.0
Material of all boxes: Cardboard
5. Explanation Using Box Example
1. Width, Height, Depth → Non-static → Each box has its own dimensions.
2. Material → Static → Shared by all boxes; changing it once affects all boxes.
3. volume() → Non-static method → Calculates volume of that specific box.
4. displayMaterial() → Static method → Shows shared material and can be called
without creating an object.
6. Key Points
Static members belong to the class, non-static members belong to objects.
Static variables save memory as there is only one copy shared by all objects.
Static methods cannot access non-static variables directly.
Box analogy:
o Width, Height, Depth = non-static
o Material = static
o Volume method = non-static
o Display material = static method
2. What is the difference between a method with a return type and a method with void as
the return type? Provide examples to show the usage of both types of methods?
[Link]
A method is a block of code that performs a specific task.
Methods in Java can either return a value (non-void) or return nothing (void).
2. Difference Between Return Type Method and Void Method
Feature Method with Return Type Method with Void Return Type
Yes, it returns a value of the specified
Returns a value No, does not return any value
type
Usage in Can be used in assignments or
Cannot be used in expressions
expressions expressions
Optional, can be used without
return statement Required to return a value
value
Example int add(int a, int b) void display(String msg)
3. Example of Method with Return Type
class Calculator {
int add(int a, int b) { // Method returns an int
return a + b;
public class TestReturnType {
public static void main(String[] args) {
Calculator c = new Calculator();
int sum = [Link](10, 20); // Using returned value
[Link]("Sum: " + sum);
}
}
Output:
Sum: 30
4. Example of Void Method
class Message {
void display(String msg) { // Method returns nothing
[Link]("Message: " + msg);
public class TestVoid {
public static void main(String[] args) {
Message m = new Message();
[Link]("Hello, Deepthi!"); // No value is returned
Output:
Message: Hello, Deepthi!
5. Conclusion
Return type methods are used when a result needs to be returned to the caller.
Void methods are used for performing actions without returning a value, like
displaying messages.
Understanding the difference helps in proper method design and code reusability.
3. Explain method overloading in Java. How does the compiler distinguish between
overloaded methods? Write an example program that demonstrates method overloading
based on different parameter types and numbers?
1. Introduction
Method overloading is the ability to create multiple methods with the same name
in a class, but with different parameter lists.
It increases code readability and reusability.
Overloaded methods must differ in:
1. Number of parameters or
2. Type of parameters or
3. Both number and type
Return type alone cannot distinguish overloaded methods.
2. How Compiler Distinguishes Overloaded Methods
During compile time, the compiler checks the method signature (method name +
parameter list) to determine which method to call.
This is called compile-time polymorphism or static polymorphism.
3. Example Program: Method Overloading
class Calculator {
// Method with two int parameters
int add(int a, int b) {
return a + b;
// Overloaded method with three int parameters
int add(int a, int b, int c) {
return a + b + c;
// Overloaded method with two double parameters
double add(double a, double b) {
return a + b;
public class TestOverloading {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Sum of 2 integers: " + [Link](10, 20));
[Link]("Sum of 3 integers: " + [Link](5, 10, 15));
[Link]("Sum of 2 doubles: " + [Link](2.5, 3.5));
4. Sample Output
Sum of 2 integers: 30
Sum of 3 integers: 30
Sum of 2 doubles: 6.0
5. Key Points
Method overloading is determined by method signature, not return type.
Allows same method name to perform different tasks depending on parameters.
Improves code clarity and maintainability.
5. What is a constructor in Java? Explain the different types of constructors (default and
parameterized). Write a program demonstrating the use of both?
1. Introduction
A constructor is a special method in Java used to initialize objects.
It is automatically called when an object is created.
Characteristics of Constructors:
1. Constructor name must be the same as the class name.
2. No return type, not even void.
3. Can be overloaded (multiple constructors with different parameters).
2. Types of Constructors
Type Description Example
Constructor with no parameters;
Default
initializes objects with default Box()
Constructor
values.
Constructor that accepts
Parameterized Box(double w,
parameters to initialize objects
Constructor double h)
with given values.
3. Example Program
class Box {
double width, height;
// Default constructor
Box() {
width = 1;
height = 1;
}
// Parameterized constructor
Box(double w, double h) {
width = w;
height = h;
}
// Method to display box dimensions
void displayDimensions() {
[Link]("Width: " + width + ", Height: " + height);
}
}
public class TestConstructor {
public static void main(String[] args) {
// Using default constructor
Box b1 = new Box();
[Link]("Box 1 (Default Constructor):");
[Link]();
// Using parameterized constructor
Box b2 = new Box(5, 10);
[Link]("Box 2 (Parameterized Constructor):");
[Link]();
}
}
4. Sample Output
Box 1 (Default Constructor):
Width: 1.0, Height: 1.0
Box 2 (Parameterized Constructor):
Width: 5.0, Height: 10.0
5. Explanation
Default constructor initializes b1 with default values (1,1).
Parameterized constructor initializes b2 with provided values (5,10).
Demonstrates constructor overloading and object initialization in Java.
5. Discuss different access control modifiers in Java. How does public, private, protected, and
default access affect access to class members? Provide examples?
1. Introduction
Access modifiers in Java are keywords that control the visibility of class members
(variables, methods, constructors).
They help in encapsulation and security by restricting access to class members.
2. Types of Access Modifiers
Modifier Access Level Example Use
public Accessible from any class in any package public int age;
private Accessible only within the same class private int salary;
protected Accessible within same package and subclasses protected int marks;
default (no keyword) Accessible only within same package int rollNo;
3. Effects on Class Members
1. public: Member is visible everywhere.
2. private: Member is visible only inside the class; cannot be accessed from outside.
3. protected: Member is visible in same package and subclasses (even in different
packages).
4. default (package-private): Member is visible only within the same package; no
keyword is used.
4. Example Program
// File: [Link] (same package)
class Student {
public String name; // Public: accessible everywhere
private int age; // Private: accessible only within class
protected double marks; // Protected: accessible in package and subclasses
int rollNo; // Default: accessible within package
// Constructor
Student(String name, int age, double marks, int rollNo) {
[Link] = name;
[Link] = age;
[Link] = marks;
[Link] = rollNo;
// Method to access private variable
int getAge() {
return age;
public class TestAccess {
public static void main(String[] args) {
Student s = new Student("Deepthi", 20, 95.5, 101);
[Link]("Name (public): " + [Link]);
[Link]("Age (private via getter): " + [Link]());
[Link]("Marks (protected): " + [Link]);
[Link]("Roll No (default): " + [Link]);
5. Sample Output
Name (public): Deepthi
Age (private via getter): 20
Marks (protected): 95.5
Roll No (default): 101
6. Key Points
public: Maximum visibility, can be accessed anywhere.
private: Minimum visibility, ensures data security.
protected: Intermediate visibility, supports inheritance.
default: Package-level visibility, no keyword used.
6)Develop a class Person with attributes name and age, and write a method displayInfo() to
print the details of the person. Instantiate two objects of this class and call the displayInfo()
method.
Algorithm:
1. Start
2. Create a class Person with:
o Instance variables name and age
o Method displayInfo() to print name and age
3. In the main method:
o Create two objects of Person class (p1 and p2)
o Assign values to name and age for each object
o Call displayInfo() for each object to display their details
4. End
2. Program
// Class definition
class Person {
// Attributes
String name;
int age;
// Method to display person details
void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("--------------------");
// Main class
public class TestPerson {
public static void main(String[] args) {
// Create first object
Person p1 = new Person();
[Link] = "Deepthi";
[Link] = 20;
// Create second object
Person p2 = new Person();
[Link] = "Ravi";
[Link] = 22;
// Call display() method
[Link]();
[Link]();
3. Sample Output
Name: Deepthi
Age: 20
--------------------
Name: Ravi
Age: 22
4. Explanation
Class Person defines the structure with attributes name and age.
Method display() prints the details of the person.
Objects p1 and p2 have their own copies of name and age.
Each object calls display() to display its details separately.
[Link] the concept of constructor overloading in Java with the help of a program that
calculates both the area and the perimeter of a rectangle?
1. Introduction
A constructor is a special method used to initialize objects.
Constructor overloading means having multiple constructors in the same class with
different parameter lists.
This allows objects to be initialized in different ways depending on the constructor
used.
Overloaded constructors differ in:
1. Number of parameters
2. Type of parameters
2. Algorithm
Aim: To calculate area and perimeter of a rectangle using constructor overloading.
1. Start
2. Create a class Rectangle with:
o Instance variables length and width
o Constructor 1: default constructor to assign default values
o Constructor 2: parameterized constructor to assign user-defined values
o Methods calculateArea() and calculatePerimeter() to compute results
3. In main method:
o Create object using default constructor, calculate and display area and
perimeter
o Create object using parameterized constructor, calculate and display area and
perimeter
4. End
3. Program
class Rectangle {
double length, width;
// Default constructor
Rectangle() {
length = 5;
width = 3;
// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
// Method to calculate area
double calculateArea() {
return length * width;
// Method to calculate perimeter
double calculatePerimeter() {
return 2 * (length + width);
public class TestRectangle {
public static void main(String[] args) {
// Using default constructor
Rectangle r1 = new Rectangle();
[Link]("Rectangle 1 (Default Constructor):");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
[Link]("----------------------");
// Using parameterized constructor
Rectangle r2 = new Rectangle(10, 7);
[Link]("Rectangle 2 (Parameterized Constructor):");
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
4. Sample Output
Rectangle 1 (Default Constructor):
Area: 15.0
Perimeter: 16.0
----------------------
Rectangle 2 (Parameterized Constructor):
Area: 70.0
Perimeter: 34.0
5. Explanation
Default constructor initializes r1 with default length 5 and width 3.
Parameterized constructor initializes r2 with length 10 and width 7.
calculateArea() and calculatePerimeter() compute the area and perimeter of each
rectangle.
Demonstrates constructor overloading, as the same class has two constructors with
different parameters.
8. Demonstrate how method overloading works in Java. Create a class Calculator with a
method add(). • add() method to add two integers. • add() method to add three integers. •
add() method to add two double values. Create multiple Calculator objects (or use the same
object) and call all the add() methods to display their results.
1. Introduction
Method overloading is the ability to define multiple methods with the same name
in a class.
Overloaded methods must have different parameter lists (number or type of
parameters).
The compiler determines which method to call based on the method signature.
This is an example of compile-time polymorphism.
2. Algorithm
Aim: Create a Calculator class to demonstrate method overloading with add() methods.
1. Start
2. Create a class Calculator with:
o add(int a, int b) to add two integers
o add(int a, int b, int c) to add three integers
o add(double a, double b) to add two double values
3. In main method:
o Create a Calculator object
o Call all three add() methods with appropriate arguments
o Display the results
4. End
3. Program
class Calculator {
// Add two integers
int add(int a, int b) {
return a + b;
// Add three integers
int add(int a, int b, int c) {
return a + b + c;
// Add two double values
double add(double a, double b) {
return a + b;
public class TestCalculator {
public static void main(String[] args) {
Calculator calc = new Calculator(); // Create object
// Call add() methods
[Link]("Sum of 2 integers: " + [Link](10, 20));
[Link]("Sum of 3 integers: " + [Link](5, 15, 25));
[Link]("Sum of 2 doubles: " + [Link](2.5, 3.7));
4. Sample Output
Sum of 2 integers: 30
Sum of 3 integers: 45
Sum of 2 doubles: 6.2
5. Explanation
1. Method Overloading:
o add() is defined three times with different parameters.
o Compiler calls the correct method based on the arguments provided.
2. Two integers added: add(10,20) → calls add(int,int)
3. Three integers added: add(5,15,25) → calls add(int,int,int)
4. Two doubles added: add(2.5,3.7) → calls add(double,double)
5. Demonstrates compile-time polymorphism using method overloading.
9. Write a java program that illustrates how 'this' keyword can be used to resolve the
ambiguity between formal parameters and instance variables?
1. Introduction
The this keyword in Java refers to the current object.
It is commonly used to distinguish instance variables from local/formal parameters
when they have the same name.
Without this, the compiler would use the local parameter instead of the instance
variable.
2. Algorithm
1. Start
2. Create a class Person with instance variables name and age.
3. Create a constructor with parameters name and age (same as instance variables).
4. Use [Link] = name and [Link] = age to assign values to instance variables.
5. Create a method display() to print name and age.
6. In main(), create objects and call display() to show values.
7. End
3. Program
class Person {
String name;
int age;
// Constructor with parameters having same names as instance variables
Person(String name, int age) {
[Link] = name; // 'this' resolves ambiguity
[Link] = age; // assigns parameter values to instance variables
// Method to display person details
void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("--------------------");
}
public class TestThisKeyword {
public static void main(String[] args) {
// Creating objects
Person p1 = new Person("Deepthi", 20);
Person p2 = new Person("Ravi", 22);
// Display details
[Link]();
[Link]();
4. Sample Output
Name: Deepthi
Age: 20
--------------------
Name: Ravi
Age: 22
--------------------
5. Explanation
The constructor parameters have the same names as the instance variables.
Without this, writing name = name; would assign the parameter to itself.
[Link] = name; assigns the parameter name to the instance variable name of the
current object.
Similarly, [Link] = age; assigns the parameter age to the instance variable age.
10. Demonstrate how a constructor initializes object attributes. Create a class Book with
attributes title and price. Create a parameterized constructor to initialize these attributes
and create multiple Book objects to display their details?
1. Introduction
A constructor is a special method used to initialize objects.
It has the same name as the class and no return type.
Using a parameterized constructor, objects can be initialized with specific values
during creation.
2. Algorithm
1. Start
2. Create a class Book with instance variables: title (String) and price (double).
3. Create a parameterized constructor with parameters title and price.
4. Inside constructor, assign parameter values to instance variables.
5. Create a method display() to show book details.
6. In main method:
o Create multiple Book objects using parameterized constructor.
o Call display() for each object.
7. End
3. Program
class Book {
String title;
double price;
// Parameterized constructor
Book(String title, double price) {
[Link] = title; // Initialize instance variable
[Link] = price; // Initialize instance variable
// Method to display book details
void display() {
[Link]("Title: " + title);
[Link]("Price: ₹" + price);
[Link]("----------------------");
public class TestBook {
public static void main(String[] args) {
// Creating Book objects using parameterized constructor
Book b1 = new Book("Java Programming", 450.50);
Book b2 = new Book("Data Structures", 500.00);
Book b3 = new Book("Algorithms", 600.75);
// Displaying details of each book
[Link]();
[Link]();
[Link]();
4. Sample Output
Title: Java Programming
Price: ₹450.5
----------------------
Title: Data Structures
Price: ₹500.0
----------------------
Title: Algorithms
Price: ₹600.75
----------------------
5. Explanation
The parameterized constructor initializes title and price for each Book object.
Each object stores its own values of title and price.
display() method prints the attributes of the object.
Demonstrates how constructors initialize object attributes at creation.
11. .Differentiate constructor overloading and method overloading. Write a java program to
illustrate method overloading to find the volume of different shapes?
🔹 Difference between Constructor Overloading and Method Overloading
Feature Constructor Overloading Method Overloading
Defining multiple constructors in the Defining multiple methods with the
Definition same class with different parameter same name but different parameter
lists. lists.
Return
Constructors do not have a return type. Methods must have a return type.
Type
Used to initialize objects in different Used to perform different tasks with
Purpose
ways. the same method name.
Called automatically when an object is
Execution Called explicitly using the object.
created.
🔹 Java Program: Method Overloading for Areas
// Aim: Demonstrate method overloading to find area of square, rectangle, and triangle
class AreaCalculator {
// Method to calculate area of a square
public double area(double side) {
return side * side;
// Method to calculate area of a rectangle
public double area(double length, double breadth) {
return length * breadth;
// Method to calculate area of a triangle
public double area(double base, double height, boolean isTriangle) {
return 0.5 * base * height;
public class Main {
public static void main(String[] args) {
AreaCalculator calc = new AreaCalculator();
double squareArea = [Link](5); // square
double rectangleArea = [Link](6, 4); // rectangle
double triangleArea = [Link](6, 8, true); // triangle
[Link]("Area of Square (side=5): " + squareArea);
[Link]("Area of Rectangle (6x4): " + rectangleArea);
[Link]("Area of Triangle (base=6, height=8): " + triangleArea);
🔹 Output
Area of Square (side=5): 25.0
Area of Rectangle (6x4): 24.0
Area of Triangle (base=6, height=8): 24.0
12)Write a Java program by creating a'student' class having the following data members:
rollNumber, name, mathMarks, phyMarks, chemMarks and methods getRequiredDetails0 -
to get required input and displayAverage0 - to calculate average marks and display it. In class
'Implement' create an object of the Student class and get the required details from user and
display the average marks of that student.
Algorithm
1. Start the program.
2. Create a Student class with data members:
o rollNumber (int)
o name (String)
o mathMarks, phyMarks, chemMarks (int)
3. Define method getRequiredDetails() to take user input for all data members.
4. Define method displayAverage() to calculate and print the average marks.
5. Create another class Implement with the main method.
6. Inside main, create an object of Student.
7. Call getRequiredDetails() and displayAverage() methods using the object.
8. End program.
Program
// Aim: Program to create Student class and calculate average marks
import [Link];
class Student {
int rollNumber;
String name;
int mathMarks, phyMarks, chemMarks;
// Method to get student details
void getRequiredDetails() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Roll Number: ");
rollNumber = [Link]();
[Link](); // consume newline
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Math Marks: ");
mathMarks = [Link]();
[Link]("Enter Physics Marks: ");
phyMarks = [Link]();
[Link]("Enter Chemistry Marks: ");
chemMarks = [Link]();
// Method to calculate and display average marks
void displayAverage() {
double average = (mathMarks + phyMarks + chemMarks) / 3.0;
[Link]("\n--- Student Details ---");
[Link]("Roll Number: " + rollNumber);
[Link]("Name: " + name);
[Link]("Average Marks: " + average);
public class Implement {
public static void main(String[] args) {
Student s = new Student();
[Link]();
[Link]();
Sample Input / Output
Input:
Enter Roll Number: 101
Enter Name: Deepthi
Enter Math Marks: 80
Enter Physics Marks: 75
Enter Chemistry Marks: 85
Output:
--- Student Details ---
Roll Number: 101
Name: Deepthi
Average Marks: 80.0
One mark answers:-
1. Tell the difference between method overloading and method overriding?
Overloading: Same method name but different parameter list (compile-time).
Overriding: Subclass redefines a parent class method (runtime).
2. What is the purpose of a constructor in a Java class?
To initialize object variables when an object is created.
3. Define the role of this keyword in Java.
this refers to the current object and resolves ambiguity between instance variables and
parameters.
4. Define an interface in Java. How is it implemented?
Interface: A collection of abstract methods.
Implemented in a class using the implements keyword.
5. Define the static keyword. How is it used in Java?
static means member belongs to the class, not the object.
Used for variables, methods, and blocks.
6. Differentiate between parameterized constructor and default constructor.
Default constructor: Takes no arguments, assigns default values.
Parameterized constructor: Accepts arguments to initialize attributes.
7. List out the various access modifiers in Java.
public, private, protected, and default (no modifier).
8. What are nested methods?
Java does not support methods inside methods directly, but inner classes can have methods.
9. What does it mean when a method is marked as private?
It can only be accessed within the same class.
10. Point out the significance of this keyword.
It refers to the current object and avoids confusion between instance variables and local
variables.
11. Define recursive method.
A method that calls itself is called a recursive method.
12. What is the output of the following code?
class Employee {
String name;
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee();
[Link] = "Alice";
Employee emp2 = emp1;
[Link] = "Bob";
[Link]([Link]);
[Link]([Link]);
Output:
Bob
Bob
13. List the various access modifiers in Java.
public, private, protected, and default.
14. What is a constructor?
A special method used to initialize objects. It has the same name as the class and no return
type.
15. Define constructor overloading.
Having more than one constructor in the same class with different parameter lists.