0% found this document useful (0 votes)
2 views33 pages

Java OOP Complete Answers

The document provides a comprehensive guide on Java programming, covering key concepts such as arrays, garbage collection, method and constructor overloading, varargs, the final keyword, superclass constructors, method overriding, and the five characteristics of object-oriented programming (OOP). It includes definitions, syntax examples, and sample code to illustrate each concept. The guide serves as a complete answer resource for Java programming modules.

Uploaded by

allurju4
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)
2 views33 pages

Java OOP Complete Answers

The document provides a comprehensive guide on Java programming, covering key concepts such as arrays, garbage collection, method and constructor overloading, varargs, the final keyword, superclass constructors, method overriding, and the five characteristics of object-oriented programming (OOP). It includes definitions, syntax examples, and sample code to illustrate each concept. The guide serves as a complete answer resource for Java programming modules.

Uploaded by

allurju4
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

JAVA PROGRAMMING

Complete Answer Guide


Module 1 & Module 2 | 10 Marks Each
Q1a. Arrays in Java — Definition, Multidimensional Syntax & Array of
Objects

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

2. Multidimensional Array Declaration Syntax


Syntax for 2D Array:
datatype[][] arrayName;
datatype[][] arrayName = new datatype[rows][cols];

// 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];

3. Java Program — Array of Objects


class Student {
int rollNo;
String name;
double marks;

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

public class ArrayOfObjects {


public static void main(String[] args) {
// Create an array of 3 Student objects
Student[] students = new Student[3];

// Initialize each object


students[0] = new Student(101, "Alice", 95.5);
students[1] = new Student(102, "Bob", 87.0);
students[2] = new Student(103, "Charlie",91.3);

// Display all students


[Link]("===== Student Records =====");
for (int i = 0; i < [Link]; i++) {
students[i].display();
}
}
}
Output:
===== Student Records =====
Roll No : 101
Name : Alice
Marks : 95.5
----------------------------
Roll No : 102
Name : Bob
Marks : 87.0
----------------------------
Q1b. Garbage Collection in Java

What is Garbage Collection?


Garbage Collection (GC) in Java is the process of automatically reclaiming memory occupied by
objects that are no longer referenced or reachable in the program. Java uses automatic memory
management through the JVM's built-in Garbage Collector, eliminating the need to manually deallocate
memory (unlike C/C++).

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.

Ways an Object Becomes Eligible for GC


• 1. Nullifying a reference: obj = null;
• 2. Reassigning a reference: obj = new OtherObject();
• 3. Object created inside a block goes out of scope
• 4. Island of isolation (objects referencing each other but unreachable from root)

Example 1 — Basic Garbage Collection with finalize()


class Demo {
int id;
Demo(int id) { [Link] = id; }

@Override
protected void finalize() {
[Link]("Object " + id + " garbage collected");
}
}

public class GCDemo {


public static void main(String[] args) {
Demo d1 = new Demo(1);
Demo d2 = new Demo(2);

// Make d1 eligible for GC


d1 = null;

// Reassign d2 — old object eligible for GC


d2 = new Demo(3);

// Request GC (not guaranteed)


[Link]();

[Link]("Main method end");


}
}
Example 2 — Island of Isolation
class Node {
Node next;
int value;
Node(int v) { [Link] = v; }

protected void finalize() {


[Link]("Node " + value + " collected");
}
}

public class IslandDemo {


public static void main(String[] args) {
Node a = new Node(10);
Node b = new Node(20);
[Link] = b;
[Link] = a; // circular reference

// Both become unreachable — island of isolation


a = null;
b = null;
[Link]();
}
}
Q2. Method Overloading and Constructor Overloading

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

Method Overloading Example


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 doubles


double add(double a, double b) {
return a + b;
}

// Concatenate strings
String add(String a, String b) {
return a + b;
}
}

public class OverloadDemo {


public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](5, 3)); // 8
[Link]([Link](1, 2, 3)); // 6
[Link]([Link](3.5, 2.1)); // 5.6
[Link]([Link]("Hello ","World")); // Hello World
}
}
B. Constructor Overloading
Constructor Overloading means defining multiple constructors in the same class with different
parameter lists. It allows objects to be created in different ways based on what information is available
at the time of creation.

Constructor Overloading Example


class Box {
double length, width, height;

// Default constructor
Box() {
length = width = height = 1.0;
[Link]("Default Box: 1x1x1");
}

// Constructor with one parameter (cube)


Box(double side) {
length = width = height = side;
[Link]("Cube Box: " + side);
}

// Constructor with all parameters


Box(double l, double w, double h) {
length = l; width = w; height = h;
[Link]("Custom Box: "+l+"x"+w+"x"+h);
}

double volume() { return length * width * height; }


}

public class BoxDemo {


public static void main(String[] args) {
Box b1 = new Box(); // Default
Box b2 = new Box(5); // Cube
Box b3 = new Box(2, 3, 4); // Custom

[Link]("Volume b1: " + [Link]());


[Link]("Volume b2: " + [Link]());
[Link]("Volume b3: " + [Link]());
}
}
Output:
Default Box: 1x1x1
Cube Box: 5.0
Custom Box: 2.0x3.0x4.0
Volume b1: 1.0
Volume b2: 125.0
Volume b3: 24.0
Q3. Varargs and Final Keyword in Java

i. Varargs (Variable-Length Arguments)


Varargs (introduced in Java 5) allows a method to accept zero or more arguments of a specified type. It
is denoted by three dots (...) after the data type. Internally, varargs are treated as an array.
Syntax:
returnType methodName(dataType... variableName) { }
Rules:
• Only one varargs parameter is allowed per method
• It must be the last parameter in the method signature
• Can be used with other parameters before it

Varargs Example
public class VarargsDemo {

// Method accepting variable number of integers


static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}

// Mixing normal and varargs params


static void display(String label, int... values) {
[Link](label + ": ");
for (int v : values) [Link](v + " ");
[Link]();
}

public static void main(String[] args) {


[Link](sum()); // 0
[Link](sum(1, 2)); // 3
[Link](sum(1, 2, 3, 4)); // 10
display("Scores", 90, 85, 78);
}
}

ii. The final Keyword


The final keyword in Java is used to restrict the user. It can be applied to variables, methods, and
classes.

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

Super Class Constructors


In Java, when a subclass object is created, the constructor of the superclass is automatically called
before the subclass constructor executes. This ensures that the inherited part of the object is properly
initialized.
The super() keyword is used to explicitly call the superclass constructor from the subclass constructor.
It must be the first statement in the subclass constructor.

Using super() to Call Superclass Constructor


class Animal {
String name;
int age;

Animal(String name, int age) {


[Link] = name;
[Link] = age;
[Link]("Animal constructor: " + name);
}
}

class Dog extends Animal {


String breed;

Dog(String name, int age, String breed) {


super(name, age); // Calls Animal's constructor
[Link] = breed;
[Link]("Dog constructor: " + breed);
}

void display() {
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("Breed: " + breed);
}
}

public class SuperDemo {


public static void main(String[] args) {
Dog d = new Dog("Rex", 3, "Labrador");
[Link]();
}
}

Using super to Access Superclass Members


[Link] is used to access hidden superclass fields or overridden methods from a
subclass.
class Shape {
String color = "Red";
void draw() {
[Link]("Drawing a Shape");
}
}

class Rectangle extends Shape {


String color = "Blue"; // hides superclass field

void draw() { // overrides superclass method


[Link](); // Call superclass method
[Link]("Drawing a Rectangle");
}

void showColors() {
[Link]("Subclass color : " + color);
[Link]("Superclass color: " + [Link]);
}
}

public class SuperMemberDemo {


public static void main(String[] args) {
Rectangle r = new Rectangle();
[Link]();
[Link]();
}
}
Q5. Method Overriding and Runtime Polymorphism

What is Method Overriding?


Method overriding occurs when a subclass provides a specific implementation of a method that is
already defined in its superclass. The method in the subclass must have the same name, same return
type, and same parameter list as the method in the superclass.
Rules for Method Overriding:
• Method name, return type, and parameters must be identical
• The subclass method cannot have a more restrictive access modifier
• static, final, and private methods cannot be overridden
• The @Override annotation is recommended for clarity

How Method Overriding Supports Runtime Polymorphism


Runtime polymorphism (Dynamic Dispatch) is achieved when a superclass reference variable points to
a subclass object. The JVM decides at runtime — not compile time — which overridden method to call,
based on the actual object type.

Example — Runtime Polymorphism with Shapes


class Shape {
void area() {
[Link]("Area of generic shape");
}
}

class Circle extends Shape {


@Override
void area() {
[Link]("Area of Circle = PI * r * r");
}
}

class Rectangle extends Shape {


@Override
void area() {
[Link]("Area of Rectangle = length * breadth");
}
}

class Triangle extends Shape {


@Override
void area() {
[Link]("Area of Triangle = 0.5 * base * height");
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Shape s; // Superclass reference
s = new Circle(); // Points to Circle object
[Link](); // Calls Circle's area()

s = new Rectangle(); // Points to Rectangle object


[Link](); // Calls Rectangle's area()

s = new Triangle(); // Points to Triangle object


[Link](); // Calls Triangle's area()
}
}
Output:
Area of Circle = PI * r * r
Area of Rectangle = length * breadth
Area of Triangle = 0.5 * base * height
In the above example, the reference variable s is of type Shape, but at runtime the JVM determines the
actual object and calls the appropriate overridden method — this is Runtime Polymorphism.
Q6. Object Oriented Concepts — Five Characteristics of OOP

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

Core OOP Concepts


1. Encapsulation
Encapsulation is the bundling of data (attributes) and methods (behaviors) into a single unit called a
class. It hides the internal state of an object and only exposes a controlled interface (using access
modifiers: private, public, protected).
class BankAccount {
private double balance; // hidden
public void deposit(double amt) { balance += amt; }
public double getBalance() { return balance; }
}

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

i. Area and Circumference of a Circle


import [Link];

public class SwitchDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("1. Area and Circumference of Circle");
[Link]("2. Prime Number Check");
[Link]("Enter choice: ");
int choice = [Link]();

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

Difference Between while and do-while


Feature while Loop do-while Loop
Type Entry-controlled loop Exit-controlled loop
Condition check Before loop body executes After loop body executes
Min executions 0 (may never execute) 1 (always executes once)
Semicolon No semicolon after while() Semicolon required after while()
Use case When execution may be skipped When body must run at least once

a. Factorial Using while Loop


import [Link];

public class FactorialWhile {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
long factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
[Link]("Factorial of " + n + " = " + factorial);
[Link]();
}
}

b. Constructor Overloading and Method Overloading


class Rectangle {
double length, width;

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

public class OverloadFull {


public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(5);
Rectangle r3 = new Rectangle(4, 6);
[Link]("r1 area: " + [Link]());
[Link]("r2 area: " + [Link]());
[Link]("r3 area: " + [Link]());
[Link]("Method area(3,4): " + [Link](3, 4));
[Link]("Method area(7) : " + [Link](7.0));
}
}
Q9. Inheritance — Definition and Types

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

Types of Inheritance in Java


1. Single Inheritance
One subclass inherits from one superclass.
class Animal { void eat() { [Link]("Eating"); } }
class Dog extends Animal { void bark() { [Link]("Barking"); } }
// Usage: Dog d = new Dog(); [Link](); [Link]();

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

4. Multiple Inheritance (via Interfaces)


Java does not support multiple inheritance through classes to avoid the 'diamond problem', but it is
supported through interfaces.
interface A { void showA(); }
interface B { void showB(); }
class C implements A, B {
public void showA() { [Link]("A"); }
public void showB() { [Link]("B"); }
}

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 setPerson(String name, int age) {


[Link] = name;
[Link] = age;
}

void displayPerson() {
[Link]("Name : " + name);
[Link]("Age : " + age);
}
}

// Parent class
class Employee extends Person {
String department;
double salary;

void setEmployee(String dept, double sal) {


department = dept;
salary = sal;
}

void displayEmployee() {
displayPerson();
[Link]("Dept : " + department);
[Link]("Salary : " + salary);
}
}

// Child class
class Manager extends Employee {
int teamSize;

void setManager(int size) {


teamSize = size;
}

void displayManager() {
displayEmployee();
[Link]("Team : " + teamSize + " members");
}
}

public class MultilevelDemo {


public static void main(String[] args) {
Manager m = new Manager();
[Link]("Alice", 35);
[Link]("Engineering", 90000.00);
[Link](10);

[Link]("===== Manager Details =====");


[Link]();
}
}
Output:
===== Manager Details =====
Name : Alice
Age : 35
Dept : Engineering
Salary : 90000.0
Team : 10 members
Q11. Narrowing and Widening Type Casting in Java

Type Casting Overview


Type casting is the process of converting a variable from one data type to another. Java supports two
types:

1. Widening (Implicit) Type Casting


Widening conversion happens automatically when a smaller type is assigned to a larger type. No data
loss occurs. The hierarchy is: byte → short → int → long → float → double.
public class WideningDemo {
public static void main(String[] args) {
byte b = 10;
short s = b; // byte -> short (auto)
int i = s; // short -> int (auto)
long l = i; // int -> long (auto)
float f = l; // long -> float (auto)
double d = f; // float-> double(auto)

[Link]("byte : " + b);


[Link]("short : " + s);
[Link]("int : " + i);
[Link]("long : " + l);
[Link]("float : " + f);
[Link]("double: " + d);
}
}

2. Narrowing (Explicit) Type Casting


Narrowing conversion requires an explicit cast because data loss might occur. The programmer must
specify the target type in parentheses.
public class NarrowingDemo {
public static void main(String[] args) {
double d = 9.99;
int i = (int) d; // explicit: 9 (decimal lost)
short s = (short) i; // explicit
byte b = (byte) s; // explicit

[Link]("double : " + d);


[Link]("int : " + i);
[Link]("short : " + s);
[Link]("byte : " + b);

// Object narrowing (downcasting)


Animal a = new Dog(); // upcasting (auto)
Dog dog = (Dog) a; // downcasting (explicit)
[Link]();
}
}
Q12. Short Note on Garbage Collector

What is the Garbage Collector?


The Garbage Collector (GC) is a component of the Java Virtual Machine (JVM) that automatically
manages memory by identifying and freeing memory occupied by objects that are no longer reachable
from the application.

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.

Uses of 'this' Keyword


1. Distinguish instance variable from local variable
class Employee {
String name;
int salary;
Employee(String name, int salary) {
[Link] = name; // '[Link]' = instance var
[Link] = salary; // 'salary' alone = param
}
}

2. Call another constructor (Constructor Chaining)


class Box {
int l, w, h;
Box() { this(1, 1, 1); } // calls 3-arg constructor
Box(int l, int w, int h) { this.l=l; this.w=w; this.h=h; }
}

3. Pass current object as argument


class Printer {
void print(Demo d) { [Link]("Printing: " + d.x); }
}
class Demo {
int x = 10;
void show(Printer p) { [Link](this); } // pass current object
}

4. Return current object (Method Chaining)


class Builder {
int x; String y;
Builder setX(int x) { this.x = x; return this; }
Builder setY(String y){ this.y = y; return this; }
void build() { [Link](x + " " + y); }
}
// Usage: new Builder().setX(5).setY("Java").build();
Q15. Object as Parameter in Java

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.

Example — Passing Object as Parameter


class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }

// Method that accepts another Point object


double distanceTo(Point other) {
int dx = this.x - other.x;
int dy = this.y - other.y;
return [Link](dx * dx + dy * dy);
}

// Method to compare two Points


boolean isSame(Point p) {
return (this.x == p.x && this.y == p.y);
}

void display() {
[Link]("Point(" + x + ", " + y + ")");
}
}

public class ObjectParamDemo {


public static void main(String[] args) {
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
Point p3 = new Point(3, 4);

[Link]();
[Link]();

[Link]("Distance p1 to p2: %.2f%n",


[Link](p2));
[Link]("p2 same as p3? " + [Link](p3));
}
}
Output:
Point(0, 0)
Point(3, 4)
Distance p1 to p2: 5.00
p2 same as p3? true
Q16. Access Specifiers and Command-Line Arguments

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

ii. Command-Line Arguments


Command-line arguments are values passed to a Java program at the time of execution from the
command prompt. They are received in the main() method as the String[] args array.
public class CmdArgs {
public static void main(String[] args) {
[Link]("Number of args: " + [Link]);
for (int i = 0; i < [Link]; i++) {
[Link]("Arg[" + i + "] = " + args[i]);
}

// Example: Add two numbers from command line


if ([Link] == 2) {
int a = [Link](args[0]);
int b = [Link](args[1]);
[Link]("Sum = " + (a + b));
}
}
}

// Run: java CmdArgs 10 20


// Output: Sum = 30
Q17. Single Inheritance in Java with Example

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;

BankAccount(String holder, double bal) {


accountHolder = holder;
balance = bal;
}

void deposit(double amount) {


balance += amount;
[Link]("Deposited: " + amount);
}

void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Insufficient funds!");
}
}

void showBalance() {
[Link]("Balance: " + balance);
}
}

// Subclass — inherits BankAccount


class SavingsAccount extends BankAccount {
double interestRate;

SavingsAccount(String holder, double bal, double rate) {


super(holder, bal); // call parent constructor
interestRate = rate;
}

void applyInterest() {
double interest = balance * interestRate / 100;
balance += interest;
[Link]("Interest applied: " + interest);
}
}

public class SingleInheritDemo {


public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount("Alice", 5000, 5);
[Link](2000);
[Link](1000);
[Link]();
[Link]();
}
}
Q18. final with Inheritance

Overview
The final keyword plays an important role when combined with inheritance. It can restrict three aspects:

1. final Variable — Constant in Inherited Class


A final variable defined in the superclass becomes a constant and retains its value in the subclass.
class MathConstants {
final double PI = 3.14159;
final double E = 2.71828;
}
class Calculator extends MathConstants {
double circleArea(double r) {
return PI * r * r; // inherits PI
}
}

2. final Method — Cannot Be Overridden


A method declared final in the superclass cannot be overridden in any subclass.
class Vehicle {
final void startEngine() {
[Link]("Engine started");
}
void accelerate() {
[Link]("Accelerating...");
}
}

class Car extends Vehicle {


// startEngine() cannot be overridden — final
@Override
void accelerate() { // This is fine
[Link]("Car accelerating!");
}
}

3. final Class — Cannot Be Extended


A final class cannot be subclassed at all.
final class SecureTransaction {
void process() { [Link]("Processing..."); }
}

// class FraudTransaction extends SecureTransaction { }


// ERROR: Cannot subclass a final class
Practical Note: Java's core classes like String, Integer, and Math are declared final for security and
performance reasons.
Q19. The super Keyword in Java — Role and Demonstration

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;

Person(String name, int age) {


[Link] = name;
[Link] = age;
[Link]("Person constructor called");
}

void display() {
[Link]("[Person] Name: " + name + ", Age: " + age);
}

String getInfo() { return "Person: " + name; }


}

class Student extends Person {


String course;
String name; // hides [Link]

Student(String personName, int age, String stuName, String course) {


super(personName, age); // USE 1: call super constructor
[Link] = stuName;
[Link] = course;
[Link]("Student constructor called");
}

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

public class SuperKeywordDemo {


public static void main(String[] args) {
Student s = new Student("Robert", 20, "Bobby", "Java");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Person constructor called
Student constructor called

[Person] Name: Robert, Age: 20


[Student] Name: Bobby, Course: Java

Subclass name : Bobby


Superclass name: Robert
This example clearly shows all three uses of super: calling the parent constructor, invoking the
overridden parent method, and accessing the hidden parent field.

You might also like