Java OOP Complete Answers
Java OOP Complete Answers
1. Definition of Array
An array in Java is a data structure that stores a fixed-size sequential collection of elements of the
same data type. Arrays are objects in Java and are stored on the heap. Each element in an array is
accessed by its numerical index, starting from 0.
Key Properties:
• Fixed in size once created
• All elements must be of the same data type
• Index starts from 0 and goes up to (length - 1)
• Arrays are objects — they inherit from [Link]
• Stored in contiguous memory locations
// Example:
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
int[][] grid = {{1,2,3},{4,5,6}}; // inline initialization
Syntax for 3D Array:
datatype[][][] arrayName = new datatype[x][y][z];
// Example:
int[][][] cube = new int[2][3][4];
// Constructor
Student(int r, String n, double m) {
rollNo = r;
name = n;
marks = m;
}
void display() {
[Link]("Roll No : " + rollNo);
[Link]("Name : " + name);
[Link]("Marks : " + marks);
[Link]("----------------------------");
}
}
Key Concepts
• An object becomes eligible for GC when no active reference points to it.
• The GC runs in the background as a low-priority daemon thread.
• [Link]() is a hint (not a guarantee) to run the GC.
• The finalize() method is called by GC just before destroying an object.
@Override
protected void finalize() {
[Link]("Object " + id + " garbage collected");
}
}
A. Method Overloading
Method Overloading is the ability of a class to have multiple methods with the same name but different
parameter lists (different number, type, or order of parameters). It is resolved at compile-time (Static
Polymorphism / Early Binding).
Rules for Method Overloading:
• Method name must be the same
• Parameters must differ in number, type, or order
• Return type alone is NOT sufficient for overloading
• Access modifiers can differ
// Concatenate strings
String add(String a, String b) {
return a + b;
}
}
// Default constructor
Box() {
length = width = height = 1.0;
[Link]("Default Box: 1x1x1");
}
Varargs Example
public class VarargsDemo {
a) final Variable
A final variable can only be assigned once — it becomes a constant.
class Circle {
final double PI = 3.14159;
double area(double r) {
// PI = 3.0; // ERROR: cannot assign to final variable
return PI * r * r;
}
}
b) final Method
A final method cannot be overridden by subclasses.
class Parent {
final void show() {
[Link]("Parent show()");
}
}
class Child extends Parent {
// void show() { } // ERROR: cannot override final method
}
c) final Class
A final class cannot be subclassed/extended. Example: [Link] is a final class.
final class Immutable {
int value;
Immutable(int v) { value = v; }
}
// class Sub extends Immutable { } // ERROR
Q4. Super Class Constructors and Super Class Members in Java
void display() {
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("Breed: " + breed);
}
}
void showColors() {
[Link]("Subclass color : " + color);
[Link]("Superclass color: " + [Link]);
}
}
Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm that organizes software around
objects rather than functions and logic. An object is an instance of a class, containing both data (fields)
and behavior (methods).
2. Inheritance
Inheritance allows a new class (subclass) to acquire the properties and behaviors of an existing class
(superclass). It promotes code reusability and establishes an IS-A relationship.
class Vehicle { void start() { [Link]("Starting"); } }
class Car extends Vehicle { void honk() { [Link]("Beep!"); } }
3. Polymorphism
Polymorphism means 'many forms'. It allows one interface to represent different underlying data types
or methods. Java supports compile-time polymorphism (method overloading) and runtime
polymorphism (method overriding).
class Animal { void sound() { [Link]("..."); } }
class Cat extends Animal { void sound() { [Link]("Meow"); } }
class Dog extends Animal { void sound() { [Link]("Woof"); } }
4. Abstraction
Abstraction hides complex implementation details and shows only the essential features of an object. In
Java, abstraction is achieved through abstract classes and interfaces.
abstract class Car {
abstract void fuelType(); // abstract method
void start() { [Link]("Car started"); }
}
class ElectricCar extends Car {
void fuelType() { [Link]("Electric"); }
}
5. Message Passing
Objects communicate with each other by sending and receiving messages (method calls). This models
real-world interactions and forms the basis of object collaboration in Java programs.
class Printer {
void print(String msg) { [Link](msg); }
}
class Office {
public static void main(String[] args) {
Printer p = new Printer();
[Link]("Hello from Office!"); // message passing
}
}
Q7. Java Program Using switch — Circle Area & Prime Number
switch (choice) {
case 1:
[Link]("Enter radius: ");
double r = [Link]();
double area = [Link] * r * r;
double circum = 2 * [Link] * r;
[Link]("Area = %.2f%n", area);
[Link]("Circumference= %.2f%n", circum);
break;
case 2:
[Link]("Enter number: ");
int n = [Link]();
boolean isPrime = true;
if (n < 2) {
isPrime = false;
} else {
for (int i = 2; i <= [Link](n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
}
[Link](n + (isPrime ? " is Prime" : " is Not
Prime"));
break;
default:
[Link]("Invalid choice!");
}
[Link]();
}
}
Sample Output (Choice 1):
Enter radius: 7
Area = 153.94
Circumference = 43.98
Sample Output (Choice 2):
Enter number: 17
17 is Prime
Q8. while vs do-while — Factorial & Constructor/Method Overloading
// Constructor Overloading
Rectangle() { length = width = 1; }
Rectangle(double side) { length = width = side; }
Rectangle(double l, double w) { length = l; width = w; }
// Method Overloading
double area() { return length * width; }
double area(double l, double w) { return l * w; }
double area(double side) { return side * side; }
}
Definition of Inheritance
Inheritance is one of the fundamental pillars of OOP. It is the mechanism by which one class
(subclass/child class) acquires the properties and behaviors (fields and methods) of another class
(superclass/parent class). It promotes code reusability, method overriding, and hierarchical
classification.
Syntax:
class Subclass extends Superclass { }
2. Multilevel Inheritance
A class inherits from a class that itself inherits from another class (chain of inheritance).
class A { void methodA() { [Link]("Class A"); } }
class B extends A { void methodB() { [Link]("Class B"); } }
class C extends B { void methodC() { [Link]("Class C"); } }
// C inherits from B which inherits from A
3. Hierarchical Inheritance
Multiple subclasses inherit from a single superclass.
class Vehicle { void move() { [Link]("Moving"); } }
class Car extends Vehicle { void drive() { [Link]("Driving"); } }
class Bike extends Vehicle { void ride() { [Link]("Riding"); } }
5. Hybrid Inheritance
A combination of two or more types of inheritance. Java supports this only through interfaces.
Q10. Java Program — Multilevel Inheritance
// Grandparent class
class Person {
String name;
int age;
void displayPerson() {
[Link]("Name : " + name);
[Link]("Age : " + age);
}
}
// Parent class
class Employee extends Person {
String department;
double salary;
void displayEmployee() {
displayPerson();
[Link]("Dept : " + department);
[Link]("Salary : " + salary);
}
}
// Child class
class Manager extends Employee {
int teamSize;
void displayManager() {
displayEmployee();
[Link]("Team : " + teamSize + " members");
}
}
How GC Works
• JVM divides heap memory into Young Generation, Old Generation, and Metaspace (Java 8+).
• New objects are allocated in the Young Generation (Eden space).
• Minor GC collects short-lived objects from the Young Generation.
• Objects that survive multiple GC cycles are promoted to Old Generation.
• Major/Full GC collects the Old Generation — more time-consuming.
GC Algorithms
• Serial GC — Single-threaded; for small applications
• Parallel GC — Multi-threaded; default in Java 8
• G1 GC (Garbage First) — Low-latency; default from Java 9+
• ZGC / Shenandoah — Ultra-low-pause collectors
finalize() Method
Before an object is garbage collected, the JVM calls its finalize() method (defined in [Link]).
This allows cleanup operations. However, since Java 9, finalize() has been deprecated.
protected void finalize() throws Throwable {
[Link]("Finalize called");
[Link]();
}
Requesting GC
[Link](); // Suggests GC run
[Link]().gc(); // Alternative
Q13. Features of Java
• 1. Simple — Java has a clean, easy-to-learn syntax derived from C/C++, eliminating complex
features like pointers and operator overloading.
• 2. Object-Oriented — Everything in Java is treated as an object, promoting modularity,
reusability, and a clear structure.
• 3. Platform Independent — Java code compiles to bytecode (.class files) which runs on any
platform having a JVM (Write Once, Run Anywhere).
• 4. Secure — Java has no pointers, a security manager, and a bytecode verifier that checks
code before execution, preventing unauthorized access.
• 5. Robust — Java eliminates common error-prone features (like explicit memory management),
has strong type checking, exception handling, and garbage collection.
• 6. Multithreaded — Java has built-in support for multithreading, allowing concurrent execution of
multiple parts of a program.
• 7. Architecture-Neutral — Java bytecode is not tied to any specific processor architecture; the
JVM abstracts the hardware.
• 8. Portable — Java programs can run on any OS/hardware without modification due to the JVM
abstraction layer.
• 9. High Performance — Java uses Just-In-Time (JIT) compilation, translating bytecode to native
machine code at runtime for improved speed.
• 10. Distributed — Java supports distributed computing through RMI, EJB, and networking APIs,
making it ideal for internet and enterprise applications.
• 11. Dynamic — Java supports dynamic loading of classes, reflection, and runtime class
information through the [Link] package.
Q14. The this Keyword in Java
What is 'this'?
The this keyword in Java is a reference variable that refers to the current object — the object on which
the method or constructor is being called. It is available within instance methods and constructors.
Concept
In Java, objects can be passed as arguments to methods, just like primitive data types. When an object
is passed, a copy of the reference (not the actual object) is passed — changes to the object's fields
inside the method affect the original object.
void display() {
[Link]("Point(" + x + ", " + y + ")");
}
}
[Link]();
[Link]();
i. Access Specifiers
Access specifiers (also called access modifiers) control the visibility and accessibility of classes,
variables, methods, and constructors in Java.
Modifier Same Class Same Package Subclass Other Package
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
What is Inheritance?
Inheritance is the mechanism by which one class (child/subclass) acquires the properties and methods
of another class (parent/superclass). The extends keyword establishes an IS-A relationship between
classes.
Single Inheritance
In single inheritance, a single subclass inherits from a single superclass. This is the simplest form of
inheritance.
// Superclass
class BankAccount {
String accountHolder;
double balance;
void showBalance() {
[Link]("Balance: " + balance);
}
}
void applyInterest() {
double interest = balance * interestRate / 100;
balance += interest;
[Link]("Interest applied: " + interest);
}
}
Overview
The final keyword plays an important role when combined with inheritance. It can restrict three aspects:
What is super?
The super keyword in Java is a reference variable used to refer to the immediate parent class object. It
has three main uses:
• 1. Access superclass instance variables (when hidden by subclass variable)
• 2. Call a superclass method (when overridden in subclass)
• 3. Call a superclass constructor using super(...)
Comprehensive Example
class Person {
String name;
int age;
void display() {
[Link]("[Person] Name: " + name + ", Age: " + age);
}
@Override
void display() {
[Link](); // USE 2: call super method
[Link]("[Student] Name: " + name
+ ", Course: " + course);
}
void showNames() {
[Link]("Subclass name : " + name);
[Link]("Superclass name: " + [Link]); // USE 3: super
field
}
}