0% found this document useful (0 votes)
5 views67 pages

final java

The document discusses key features of Java, including its object-oriented nature, platform independence through bytecode and the Java Virtual Machine (JVM), and security measures like bytecode verification and sandboxing. It also covers concepts such as dynamic initialization, type conversion vs. type casting, variable scope and lifetime, final and blank final variables, constructors and their overloading, static vs. instance members, and garbage collection. Additionally, it emphasizes best practices for resource management and the limitations of relying on the finalize() method.

Uploaded by

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

final java

The document discusses key features of Java, including its object-oriented nature, platform independence through bytecode and the Java Virtual Machine (JVM), and security measures like bytecode verification and sandboxing. It also covers concepts such as dynamic initialization, type conversion vs. type casting, variable scope and lifetime, final and blank final variables, constructors and their overloading, static vs. instance members, and garbage collection. Additionally, it emphasizes best practices for resource management and the limitations of relying on the finalize() method.

Uploaded by

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

1. Explain the key features of Java.

Discuss how Platform Independence and Security are


achieved in the Java environment, referencing the Java Virtual Machine (JVM) and the
Bytecode concept.

Key Features of Java

1. Object‑oriented – everything is an object; inheritance, polymorphism, and encapsulation are


built‑in.

2. Simple & Familiar – syntax is close to C/C++, with automatic memory management (garbage
collection).

3. Robust – strong type checking, exception handling, and runtime checks reduce bugs.

4. Secure – the runtime environment (JVM) runs code in a sandbox and provides a security
manager.

5. Multithreaded – built‑in support for concurrent programming via threads and synchronization.

6. High Performance – just‑in‑time (JIT) compilation and optimized bytecode execution.

Platform Independence

- Java source code is compiled into bytecode (.class files), an intermediate binary format that is
not tied to any specific hardware or OS.

- The Java Virtual Machine (JVM) interprets or JIT‑compiles this bytecode at runtime, translating
it into machine‑specific instructions. Because every platform that provides a JVM can execute the
same bytecode, the same .jar file runs on Windows, Linux, macOS, Android, etc., without
modification.

Security in the Java Environment

- Bytecode Verification: When a class is loaded, the JVM’s verifier checks that the bytecode
adheres to Java’s safety rules (no illegal operand stack manipulations, no type violations, etc.).
This prevents malicious or corrupted code from causing system crashes or accessing memory
arbitrarily.

- Sandboxing: The JVM runs code in a restricted environment; untrusted applets or plugins are
denied direct access to the host filesystem, network, or native libraries unless explicitly permitted
by a security policy.

- Class Loader Namespace: Each class loader defines its own namespace, preventing unauthorized
classes from substituting core Java classes.

- Security Manager (deprecated in newer editions): Historically, it enforced fine‑grained


permissions; modern Java relies on modularization (JPMS) and the inherent safety of the bytecode
verification process.

2. Describe the concept of Dynamic Initialization in Java. Provide a simple code example
demonstrating how a variable's initial value can be calculated at runtime.

Dynamic Initialization in Java


Dynamic initialization means you don’t have to assign a constant value when you declare a
variable. Instead, the initial value is computed at runtime, often using other variables, method
calls, or user input.

Example

public class DynamicInitDemo {

public static void main(String[] args) {

// Values that will determine the initial value

int a = 5;

int b = 7;

// Variable 'sum' is initialized with a runtime calculation

int sum = a + b; // dynamic initialization

[Link]("Sum = " + sum); // Output: Sum = 12

In this snippet, sum isn’t given a literal constant; its value is the result of the expression a + b,
which is evaluated when the program runs. You can replace a + b with any runtime logic—
reading input, calling methods, etc.—to achieve dynamic initialization.

3. Explain the difference between Type Conversion and Type Casting in Java. Provide a scenario
and accompanying code to illustrate both widening (implicit) and narrowing (explicit)
conversions.

Type conversion vs. type casting

In Java a type conversion is any change of a value from one primitive type to another. When the
conversion can be done safely without losing data, the compiler does it automatically – that’s a
widening conversion. When the conversion might lose information, you must tell the compiler
you’re okay with it – that’s a narrowing conversion and you use a cast (the explicit syntax).

Scenario

You have a temperature reading that starts as an int (Celsius × 10) and you want to display it as a
double (Celsius). Later you need to store the value back into a byte for a low‑power device, which
can only hold values 0‑255.

public class TempConverter {

public static void main(String[] args) {

// original reading: 23.5°C → stored as int (235)

int reading = 235; // int → int (no change)


// Widening (implicit) conversion: int → double

double celsius = reading / 10.0; // 23.5

[Link]("Temperature: " + celsius + "°C");

// Narrowing (explicit) conversion: double → byte

// We know the temperature will be between 0 and 25.5°C, so 0‑255 fits.

byte compact = (byte) (celsius * 10); // cast tells the compiler we accept possible loss

[Link]("Compact value for device: " + compact);

- int → double is a widening conversion; the compiler does it automatically because a double can
represent every int value.

- double → byte is a narrowing conversion; we must use a cast (byte) to tell the compiler we’re
aware that the value may be truncated.

Key points

- Conversion is the general idea of changing types.

- Casting is the explicit syntax you use for narrowing conversions.

- Widening conversions are implicit and safe; narrowing conversions require a cast and can lose
data.

4. Define scope and lifetime of a variable in Java. Use a code snippet involving loops or block
statements to clearly demonstrate how a variable's scope affects its lifetime.

Scope is the region of the program where a variable can be referenced. It’s determined by where
the declaration appears—inside a class, a method, a block, or a loop.

Lifetime (or extent) is how long the variable stays alive in memory. It begins when execution
enters the scope and ends when that scope finishes.

public class ScopeDemo {

static int classVar = 1; // class scope, lives as long as the class is loaded

public static void main(String[] args) {

int methodVar = 2; // method scope, created when main starts

if (methodVar > 0) {

int blockVar = 3; // block scope, created here


[Link]("Inside if: " + blockVar);

} // blockVar goes out of scope here; its lifetime ends

for (int i = 0; i < 2; i++)

int loopVar = i * 10; // loop scope, created each iteration

[Link]("Loop iteration " + i + ": " + loopVar);

} // loopVar goes out of scope here

// [Link](blockVar); // ← compile‑time error: blockVar not in scope

// [Link](loopVar); // ← compile‑time error: loopVar not in scope

- classVar is visible everywhere in the class and lives until the program terminates.

- methodVar is visible only inside main; it exists from the start of main until it returns.

- blockVar exists only within the if block; once the block ends, it’s gone.

- loopVar is recreated on each iteration of the for loop, so its lifetime is limited to a single loop
cycle.

The example shows that a variable’s scope determines where you can use it, and its lifetime ends
as soon as execution leaves that scope.

5. What are Final and Blank Final variables in Java? Explain the rules for initialization for each,
and discuss the primary use case for using a blank final variable.

Final variables

A variable declared with the final keyword can be assigned only once. After that assignment the
value (or reference) cannot be changed.

Initialization rules

- Compile‑time constant: If the variable is a primitive or a String and is initialized with a literal
(or an expression made only of constants), the compiler treats it as a constant and you must
provide the initializer at the declaration.

- Instance / static final fields: Must be initialized either in the declaration, in every constructor (for
instance fields), or in a static initializer block (for static fields). The compiler guarantees that
every possible execution path assigns a value exactly once.

Blank final variables

A blank final is a final variable that is not initialized at its declaration. It must be assigned a value
later, but still only once.
Initialization rules

- For a local blank final, you must assign it a value before you use it, and the assignment must
happen exactly once along every possible execution path.

- For an instance blank final field, you must assign it in every constructor (or in an instance
initializer block) – the compiler checks that each constructor guarantees an assignment.

- For a static blank final field, you must assign it in a static initializer block (or directly in the
declaration, which would make it non‑blank).

Primary use case for a blank final

You need a value that is known only at runtime (e.g., based on user input, configuration, or a
computation) but you still want to enforce that the variable cannot be changed after it’s set. This
gives you the safety of final while allowing flexible initialization.

class Config {

// blank final – value comes from the environment at startup

private final String appMode;

// constructor receives the mode; it must be assigned exactly once

Config(String mode) {

[Link] = mode; // first and only assignment

public String getMode() {

return appMode; // cannot be reassigned later

6. What is a Constructor in Java? Explain the two main roles of a constructor. Provide a program to
illustrate constructor overloading.

Constructor in Java

A constructor is a special method that is invoked when an object is instantiated. Its name must
match the class name, and it has no return type (not even void).

Two main roles

1. Object initialization – set the initial state of the new instance (assign field values, allocate
resources, etc.).

2. Overloading support – provide multiple ways to create an object, letting callers choose the most
convenient set of arguments.
Constructor overloading example

public class Person {

private final String name;

private final int age;

private final String address;

// Constructor with name and age

public Person(String name, int age) {

this(name, age, "Unknown"); // delegate to the 3‑arg constructor

// Constructor with name, age, and address

public Person(String name, int age, String address) {

[Link] = name;

[Link] = age;

[Link] = address;

// No‑arg constructor (default values)

public Person() {

this("John Doe", 0, "Earth");

@Override

public String toString() {

return [Link]("Person{name='%s', age=%d, address='%s'}",

name, age, address);

// Simple test

public static void main(String[] args) {

Person p1 = new Person("Alice", 30);


Person p2 = new Person("Bob", 25, "New York");

Person p3 = new Person();

[Link](p1);

[Link](p2);

[Link](p3);

Running main prints:

Person{name='Alice', age=30, address='Unknown'}

Person{name='Bob', age=25, address='New York'}

Person{name='John Doe', age=0, address='Earth'}

The class demonstrates constructor overloading: three constructors with different parameter lists,
each fulfilling the role of initializing the object while giving callers flexibility.

7. Differentiate between static members (variables and methods) and instance members. Explain
the usage of the static keyword, and state why a non-static member cannot be referenced from a
static method.

Static vs. instance members

- Static members belong to the class itself. There is only one copy of a static variable, and a static
method can be called without creating an object. They are accessed with the class name
([Link] or [Link]()).

- Instance members belong to each object (instance) of the class. Every object gets its own copy
of an instance variable, and an instance method works on that particular object’s state. They are
accessed through a reference ([Link] or [Link]()).

*The static keyword*

- When applied to a variable, it makes the variable a class‑level variable that is shared across all
instances.

- When applied to a method, it makes the method callable without an instance; the method can
only touch static data or call other static methods directly.

- Static blocks (static { … }) run once when the class is loaded, useful for one‑time initialization
of static fields.

Why a non‑static member can’t be referenced from a static method

A static method runs in a context where no specific object exists. It has no this reference to an
instance, so it cannot reach instance variables (which hold per‑object state) or call instance
methods (which may depend on that state). The compiler therefore forbids the reference to keep
the program well‑defined.

Illustrative code

public class Counter {

// static (class‑level) variable

private static int totalInstances = 0;

// instance variable

private int id;

// static block – runs once when the class is loaded

static {

[Link]("Class Counter loaded.");

// constructor increments the static count and sets the instance id

public Counter() {

totalInstances++;

[Link] = totalInstances; // each object gets a unique id

// static method – can use only static members

public static int getTotalInstances() {

// id++; // ← compile‑time error: non‑static variable id cannot be referenced

return totalInstances;

// instance method – can use both static and instance members

public int getId() {

return [Link];

public static void main(String[] args) {

[Link]("Before objects: " + [Link]()); // 0


Counter c1 = new Counter();

Counter c2 = new Counter();

[Link]("c1 id: " + [Link]()); // 1

[Link]("c2 id: " + [Link]()); // 2

[Link]("Total instances: " + [Link]()); // 2

- totalInstances is static – all objects share the same count.

- id is an instance variable – each object has its own value.

- getTotalInstances() is static, so it can only read totalInstances; trying to use id would be illegal
because there is no this object to refer to.

This restriction ensures that static methods remain independent of any particular instance’s state.

8. Explain the concept of Garbage Collection in Java. Describe the role of the Garbage Collector,
and explain why Java programs should not rely on the finalize() method for critical resource
cleanup.

Garbage Collection (GC) in Java

Java’s GC is an automatic memory‑management system that runs as a background thread. It


tracks objects that are no longer reachable from any live reference (the “roots” such as stack
variables, static fields, etc.) and reclaims the heap space they occupy. By doing this continuously,
the JVM prevents memory leaks and lets developers focus on business logic instead of manual
deallocation.

What the Garbage Collector does

- Identifies unreachable objects – using a mark‑and‑sweep (or a generational variant) algorithm.

- Frees their memory – the heap space becomes available for new allocations.

- Compacts the heap (optional) – reduces fragmentation, improving locality and allocation speed.

*Why not rely on finalize() for critical cleanup*

1. Unpredictable execution – the GC decides when (or if) finalize() runs; there’s no guarantee it
will happen before the program exits.

2. Performance overhead – objects that implement finalize() are treated specially; they often
survive an extra GC cycle, which can delay reclamation.
3. Resurrection risk – finalize() can store a reference to the object somewhere else, making it
reachable again and creating subtle bugs.

4. Deprecated – since Java 9, finalize() is marked for removal; the recommended replacement is
explicit resource management (try‑with‑resources, Closeable, etc.).

Preferred pattern for resource cleanup

public class Resource implements AutoCloseable {

public Resource() {

// acquire native resource (file, socket, etc.)

@Override

public void close() {

// release the resource reliably

// Usage

try (Resource r = new Resource()) {

// use r

} // close() is called automatically, even if an exception occurs

In short, the GC frees memory automatically, but for things like file handles, network
connections, or native resources you should use deterministic cleanup (e.g., try‑with‑resources)
rather than relying on finalize().

Let me know if you’d like a deeper dive into any specific GCalgorithm or more examples of safe
resource handling.

9. Explain the purpose of the this keyword. Provide code examples to demonstrate its use for two
different purposes: accessing instance variables and calling a constructor from another
constructor.

*this in Java* is a reference to the current object. It lets you:

1. Distinguish instance fields from parameters or local variables.

2. Invoke one constructor from another (constructor chaining).

1. Accessing instance variable

class Person {
private String name;

private int age;

// constructor receives parameters with the same names as fields

Person(String name, int age) {

[Link] = name; // “[Link]” is the field, “name” is the parameter

[Link] = age;

void display() {

[Link]("Name: " + [Link] + ", Age: " + [Link]);

[Link] and [Link] refer to the object’s fields, not the constructor parameters

2. Calling a constructor from another constructor

class Rectangle {

private double width;

private double height;

// constructor that takes both dimensions

Rectangle(double width, double height) {

[Link] = width;

[Link] = height;

// overloaded constructor – calls the two‑arg constructor

Rectangle(double side) {

this(side, side); // creates a square by reusing the logic above

void area() {

[Link]("Area = " + ([Link] * [Link]));


}

this(side, side) invokes the primary constructor, avoiding code duplication.

10. Describe the different parameter passing mechanisms in Java (e.g., Pass-by-Value for
primitives and reference values). Use a code example to explain why changes made to an object
inside a method are reflected outside the method.

Parameter passing in Java

Java always uses pass‑by‑value.

- For primitive types (int, double, char, …) the actual value is copied onto the method’s stack
frame.

- For object references the value that is copied is the reference (the address that points to the
object). The object itself lives on the heap and is not copied.

Because the reference is copied, a method can reach the same object that the caller sees, so any
changes to the object’s internal state are visible outside the method. Reassigning the reference
inside the method only affects the local copy and does not change the caller’s reference.

Example

public class PassDemo {

// method that swaps two integers – it won’t affect the caller

static void swapInts(int a, int b) {

int tmp = a;

a = b;

b = tmp; // a and b are copies of the original values

// method that modifies an object's state

static void incrementAge(Person p) {

[Link]++; // p is a copy of the reference, but it points to the same Person object

public static void main(String[] args) {

int x = 5, y = 10;

swapInts(x, y);
[Link]("x = " + x + ", y = " + y); // prints x = 5, y = 10

Person alice = new Person("Alice", 30);

incrementAge(alice);

[Link]([Link] + " is now " + [Link]); // prints Alice is now 31

class Person {

String name;

int age;

Person(String name, int age) {

[Link] = name;

[Link] = age;

- swapInts receives copies of the primitive values, so swapping inside the method does nothing to
x and y in main.

- incrementAge receives a copy of the reference stored in alice. Both the copy (p) and the original
variable (alice) point to the same Person object, so the increment is visible after the call.

Thus, Java’s pass‑by‑value semantics explain why primitive arguments are isolated, while object
state changes are shared across method boundaries.

11. Explain the concept of Dynamic Method Dispatch (Runtime Polymorphism). Provide a detailed
code example involving a parent class and two child classes to illustrate how a method call is
resolved at runtime.

Dynamic Method Dispatch (Runtime Polymorphism

When a program invokes an overridden method through a reference variable, the actual method
that runs is determined by the object that the reference points to, not by the reference’s declared
type. This decision is made at runtime, hence the name dynamic (or runtime) method dispatch. It
lets you write code that works with a general type (the parent class) while the specific behavior is
supplied by the concrete subclass that’s created at runtime.

Example

// Parent class

class Animal {
void speak() {

[Link]("Some generic sound");

// Child 1

class Dog extends Animal {

@Override

void speak() {

[Link]("Woof!");

// Child 2

class Cat extends Animal {

@Override

void speak() {

[Link]("Meow!");

// Driver

public class RuntimePolymorphismDemo {

public static void main(String[] args) {

Animal[] zoo = new Animal[3];

zoo[0] = new Animal(); // reference type Animal, object type Animal

zoo[1] = new Dog(); // reference Animal, object Dog

zoo[2] = new Cat(); // reference Animal, object Cat

for (Animal a : zoo) {

[Link](); // <-- resolved at runtime based on the actual object


}

Output

Some generic sound

Woof!

Meow!

What happens internally

1. The compiler sees the call [Link]() and only checks that Animal has a speak() method. It
generates bytecode that invokes the method on the object referenced by a.

2. At runtime the JVM looks at the actual object stored in a (the runtime type). If the object is a
Dog, the [Link]() implementation runs; if it’s a Cat, [Link]() runs, and so on.

3. Because the decision is made while the program is executing, you can add new subclasses (e.g.,
Bird) without touching the existing dispatch code – the correct speak() will be called
automatically.

This mechanism is the backbone of many design patterns (Strategy, Factory, etc.) and enables
flexible, extensible software where behavior is supplied by concrete classes rather than
hard‑coded conditionals.

12. Compare and contrast Abstract Classes and Interfaces. Provide at least three key differences in
terms of implementation, inheritance, and usage of constructors.

Abstract Classes vs. Interfaces in Java

Both are tools for abstraction and defining blueprints, but they serve different purposes

Key Differences

1. Implementation

- Abstract Class: Can have both abstract methods (no body) and concrete methods (with
implementation).

- Interface: Can only declare abstract methods (no implementation) except for default and static
methods (Java 8+) and private methods (Java 9+).

2. Inheritance

- Abstract Class: A class can extend one abstract class (single inheritance).

- Interface: A class can implement multiple interfaces (multiple inheritance of type).

3. Constructors
- Abstract Class: Can have constructors (called when a subclass is instantiated).

- Interface: Cannot have constructors; interfaces are purely behavioral blueprints.

Example

// Abstract class

abstract class Vehicle {

private String brand;

Vehicle(String brand) {

[Link] = brand;

void showBrand() {

[Link]("Brand: " + brand);

abstract void drive();

// Interface

interface Electric {

void charge();

// Concrete class

class TeslaModelS extends Vehicle implements Electric {

TeslaModelS() {

super("Tesla"); // calls Vehicle's constructor

@Override

void drive() {

[Link]("Driving silently...");

}
@Override

public void charge() {

[Link]("Charging battery...");

- Vehicle is an abstract class that provides common state (brand) and behavior (showBrand()),
plus a contract (drive()).

- Electric is an interface that defines a behavior (charge()).

- TeslaModelS inherits from Vehicle and implements Electric, fulfilling both contracts.

When to use which?

- Use an abstract class when subclasses share common implementation or state.

- Use an interface to define a contract that unrelated classes might implement (e.g., Runnable,
Comparable).

13. Discuss the usage of the super keyword. Provide a code snippet demonstrating how super can be
used to call a parent class constructor and to access a shadowed member variable of the
parent class.

*The super keyword* is a reference to the immediate superclass of the current object. It is used in
two common ways:

1. To invoke a superclass constructor – super(...) must be the first statement in a subclass


constructor.

2. To access a member (method or variable) that is hidden by a subclass – [Link] reaches


the parent’s version.

Below is a compact example that shows both usages.

class Animal {

protected String name = "Generic Animal";

Animal(String name) {

[Link] = name;

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

void speak() {

[Link](name + " makes a sound");


}

class Dog extends Animal {

private String name = "Dog"; // shadows [Link]

Dog(String name) {

super(name); // call the parent constructor

[Link]("Dog constructor: " + name);

@Override

void speak() {

[Link](); // call the parent's implementation

[Link]("Woof!");

void showNames() {

[Link]("[Link] (Dog) = " + [Link]);

[Link]("[Link] (Animal) = " + [Link]);

public class SuperDemo {

public static void main(String[] args) {

Dog d = new Dog("Buddy");

[Link]();

[Link]();

What the code demonstrates

- Dog(String name) uses super(name) to invoke Animal’s constructor, initializing the shared state.
- Inside speak(), [Link]() calls the parent’s version before adding Dog‑specific behavior.

- showNames() prints two different name fields: [Link] (the one declared in Dog) and
[Link] (the one inherited from Animal).

Running the program yields:

Animal constructor: Buddy

Dog constructor: Buddy

Buddy makes a sound

Woof!

[Link] (Dog) = Dog

[Link] (Animal) = Buddy

The super keyword thus lets a subclass collaborate with its superclass, whether by delegating
construction or by reaching hidden members.

14. Explain the rules of Access Control Protection for members within a Package. Describe the
visibility of a member declared with the default (no keyword), public, protected, and private
access specifiers.

Access‑control rules in Java (package‑level view)

When a class, field, method, or constructor is declared inside a package, its visibility is governed
by the access modifier you use (or by the default “package‑private” when you omit a modifier).
The four possibilities are:

1. *private* – only inside the same class

A private member cannot be seen by any other class, not even by classes in the same package. It is
the most restrictive level.

2. default (no keyword) – “package‑private” – only inside the same package

If you write nothing after the declaration, the member is accessible to every class that belongs to
the same package, but not to classes outside that package (including subclasses).

3. *protected* – inside the same package or in subclasses

A protected member is visible to all classes in the same package and to any subclass, even if the
subclass lives in a different package.

4. *public* – everywhere

A public member can be accessed from any class, regardless of package.

Quick illustration

// File: pkg1/[Link]
package pkg1;

public class A {

private int aPrivate; // only A sees it

int aDefault; // pkg1.* can see it

protected int aProtected; // pkg1.* and subclasses anywhere

public int aPublic; // anyone can see it

// File: pkg1/[Link]

package pkg1;

public class B {

void test(A obj) {

[Link] = 1; // ❖ compile‑time error (private)

[Link] = 2; // ✔ ok (same package)

[Link] = 3; // ✔ ok (same package)

[Link] = 4; // ✔ ok

// File: pkg2/[Link]

package pkg2;

import pkg1.A;

public class Cextends A {

void test(A obj) {

[Link] = 1; // ❖ error (private)

[Link] = 2; // ❖ error (different package, default)

[Link] = 3; // ✔ ok (protected via inheritance)

[Link] = 4; // ✔ ok

}
}

Private stays hidden inside A.

- Default is only visible to other classes that live in pkg1.

- Protected is visible to pkg1 classes and to any subclass such as C in pkg2.

- Public is visible everywhere.

These rules let you control how much of a class’s internal state is exposed, helping you enforce
encapsulation while still allowing flexible reuse across packages.

15. Differentiate between Checked Exceptions and Unchecked Exceptions (Runtime Exceptions).
Provide an example of each and explain the Java compiler's mandatory handling rule for checked
exceptions.

Checked vs. Unchecked Exceptions

- Checked exceptions are subclasses of Exception (but not RuntimeException). The compiler
forces you to either catch them or declare them in the method signature. They represent
recoverable, anticipated error conditions (e.g., file not found, network failure).

- Unchecked exceptions (runtime exceptions) are subclasses of RuntimeException. The compiler


does not require them to be caught or declared. They usually indicate programming errors (e.g.,
NullPointerException, ArrayIndexOutOfBoundsException)

Example of a checked exception

import [Link].*;

public class CheckedDemo {

// The compiler will enforce handling of IOException

public static void readFile(String path) throws IOException {

BufferedReader br = new BufferedReader(new FileReader(path));

try {

String line;

while ((line = [Link]()) != null) {

[Link](line);

} finally {

[Link](); // make sure the resource is released


}

public static void main(String[] args) {

try {

readFile("[Link]");

} catch (IOException e) {

[Link]("Could not read file: " + [Link]());

`IOException` is a checked exception. The method readFile either catches it or declares throws
IOException. The caller must handle it, otherwise the code won’t compile

Example of an unchecked exception

public class UncheckedDemo {

public static void divide(int a, int b) {

[Link](a / b); // may throw ArithmeticException if b == 0

public static void main(String[] args) {

divide(10, 0); // runtime error – no compile‑time enforcement

ArithmeticException (a subclass of RuntimeException) is unchecked; the compiler does not


require a try‑catch or a throws clause.

Compiler rule for checked exceptions

When a method can throw a checked exception, the method must either:

1. Catch the exception within a try‑catch block, or

2. Declare the exception in its signature using throws.

If neither is done, compilation fails with an error like “unreported exception X; must be caught or
declared to be thrown”.
Unchecked exceptions have no such requirement, which is why they can propagate silently unless
you explicitly handle them.

16. Explain the purpose and usage of the five exception handling keywords: try, catch, throw,
throws, and finally. Describe a scenario where the finally block is essential.

try / catch / throw / throws / finally

- *try* – marks a block of code that might raise an exception. The JVM watches this block; if an
exception occurs, control jumps out of the block to a matching catch.

- *catch* – follows a try and specifies the exception type you want to handle. When the thrown
exception is an instance of the declared type (or a subclass), the code inside the catch runs.

- *throw* – explicitly creates and throws an exception object. You use it when you detect an error
condition and want to signal it upward.

- *throws* – appears in a method signature to declare that the method may throw one or more
checked exceptions. It doesn’t handle the exception; it just informs callers that they must handle
it.

- *finally* – optional block after try (and any catch). It always executes, whether the try finishes
normally, a catch handles an exception, or even if the method returns early. It’s the place for
cleanup code (closing files, releasing locks, etc.).

*When finally is essential*

Whenever you acquire a resource that must be released—like opening a file, a database
connection, or a lock—finally guarantees the release happens even if something goes wrong.

public static String readFirstLine(String path) throws IOException {

BufferedReader br = null;

try {

br = new BufferedReader(new FileReader(path));

return [Link](); // may throw IOException

} catch (IOException e) {

[Link]("Error reading file: " + [Link]());

throw e; // re‑throw after logging

} finally {

if (br != null) {

[Link](); // always executed

}
}

In this example, [Link]() runs whether readLine succeeds, throws an IOException, or the catch
block re‑throws the exception. Without finally, the file could stay open, leading to resource leaks.

17. Write a detailed note on creating your own Exception subclasses. Explain the process, and
provide a code example demonstrating how to define a custom exception and use the throw
keyword to signal it.

Creating your own exception type is a handy way to signal domain‑specific error conditions and
keep your code’s error handling expressive. The process is straightforward:

1. Pick a base class – For a checked exception extend Exception (or a subclass of it). For an
unchecked (runtime) exception extend RuntimeException.

2. Add constructors – At minimum provide a no‑arg constructor and one that takes a message (and
optionally a cause). This mirrors the constructors that the standard exceptions have.

3. Optionally add fields or methods – If you want to carry extra context (e.g., an error code), store
it in fields and expose getters.

Below is a tiny example that models a “InsufficientBalance” error for a bank account. It’s a
checked exception, so callers must either catch it or declare it in their throws clause.

// Custom checked exception

public class InsufficientBalanceException extends Exception {

private final double shortfall; // how much we were short

// No‑arg constructor

public InsufficientBalanceException() {

this(0.0);

// Constructor with message

public InsufficientBalanceException(double shortfall) {

super("Cannot withdraw that amount – shortfall: " + shortfall);

[Link] = shortfall;

// Getter for extra info

public double getShortfall() {


return shortfall;

// A simple bank account that uses the custom exception

public class BankAccount {

private double balance

public BankAccount(double initialBalance) {

[Link] = initialBalance;

public void withdraw(double amount) throws InsufficientBalanceException {

if (amount > balance) {

double missing = amount - balance;

throw new InsufficientBalanceException(missing); // signal the error

balance -= amount;

[Link]("New balance: " + balance);

public static void main(String[] args) {

BankAccount acct = new BankAccount(100.0);

try {

[Link](150.0); // this will trigger the custom exception

} catch (InsufficientBalanceException e) {

[Link]([Link]());

[Link]("You are short by: " + [Link]());

}
What’s happening here?

- InsufficientBalanceException extends Exception, so it’s a checked exception.

- The class stores the amount that couldn’t be covered (shortfall) and provides a getter.

- In [Link], when the requested amount exceeds the available balance we throw a
new instance of our custom exception, passing the missing amount to the constructor.

- The main method catches the exception, prints the message, and uses the extra shortfall
information.

By defining your own exception types you make the error flow self‑documenting, and because the
compiler treats checked custom exceptions like any other checked exception, you’re forced to
handle them explicitly—exactly what you want for recoverable, domain‑specific errors.

If you ever need an unchecked version, just change the base class to RuntimeException and you
won’t have to declare it in throws clauses. Hope that clears it up! Let me know if you’d like a
version with a custom unchecked exception or any other tweak.

18. Compare the String class and the StringBuffer class. Explain when and why you should
choose one over the other in a Java program, focusing on the concept of mutability.

String vs. StringBuffer

String and StringBuffer are both used to store sequences of characters, but they differ
fundamentally in mutability.

| Aspect | String | StringBuffer |

| Mutability | Immutable – once created the character sequence cannot change. Any operation that
appears to modify a String actually returns a new String object. | Mutable – the internal character
array can be changed in‑place; operations modify the same object. |

| Thread‑safety | Not synchronized, but because it is immutable it is inherently safe to share across
threads. | Synchronized – every mutating method is synchronized, making it safe for concurrent
use at the cost of extra overhead. |

| Performance for repeated modifications | Poor – each concatenation or replacement creates a


new String and discards the old one, leading to many temporary objects and extra
garbage‑collection work. | Good – appending, inserting, or deleting characters updates the internal
buffer without allocating new objects each time. |

| Typical use‑case | When the text is fixed or rarely changed (e.g., constants, keys in maps,
logging messages). | When you need to build or modify a string dynamically, such as in loops that
concatenate many values, or when constructing SQL statements, JSON payloads, etc.

Why mutability matters

Because a String is immutable, the JVM can cache its hash code, intern it, and safely share it. This
makes String fast for read‑only operations and safe for multi‑threaded access.
StringBuffer sacrifices some of that safety (through synchronization) to allow the same buffer to
be changed repeatedly. If you need frequent changes and don’t require thread safety, Java also
offers StringBuilder, which is the same as StringBuffer but without synchronization, giving even
better performance.

When to choose which

_Use String when_

- The value does not change after creation.

- The value is a constant or a key (e.g., map keys, configuration constants).

- You want the benefits of immutability (thread safety, hash‑code caching).

_Use StringBuffer or StringBuilder) when_

- You are building a string incrementally (e.g., inside a loop).

- You need to insert, delete, or replace characters many times.

- You are dealing with a mutable text that must be shared across threads and need the built‑in
synchronization (StringBuffer).

Simple example

// Using String (creates many temporary objects)

String s = "";

for (int i = 0; i < 5; i++) {

s += i; // each iteration creates a new String

[Link](s); // 01234

// Using StringBuffer (single mutable buffer)

StringBuffer sb = new StringBuffer();

for (int i = 0; i < 5; i++) {

[Link](i); // modifies the same buffer

[Link]([Link]()); // 01234

In the first loop, five intermediate String objects are allocated; in the second loop, only one
StringBuffer object is used. For small loops the difference is negligible, but for large or frequent
operations the mutable approach is far more efficient.
19. Discuss the role of Wrapper Classes in Java. Explain the process of Autoboxing and Unboxing
with a simple code example.

Wrapper Classes in Java

Wrapper classes provide an object representation for the eight primitive types (int, char, byte,
short, long, float, double, boolean). They let primitives be used in contexts that require objects—
e.g., collections, generics, or APIs that expect Object.

| Primitive | Wrapper |

|-----------|---------|

| int | Integer |

| char | Character |

| byte | Byte |

| short | Short |

| long | Long |

| float | Float |

| double | Double |

| boolean | Boolean |

Autoboxing – the compiler automatically converts a primitive value into its corresponding
wrapper object when an object is expected.

Unboxing – the reverse: the compiler extracts the primitive value from the wrapper object when a
primitive is needed.

Simple example

import [Link];

import [Link];

public class AutoboxDemo {

public static void main(String[] args) {

// Autoboxing: int → Integer

Integer iObj = 42; // equivalent to Integer iObj = [Link](42);

// Unboxing: Integer → int

int iPrim = iObj; // equivalent to int iPrim = [Link]();

// Using wrappers in a collection (cannot hold primitives)


List<Integer> numbers = new ArrayList<>();

[Link](1); // autoboxing: int → Integer

[Link](2);

[Link](3);

int sum = 0;

for (Integer n : numbers) {

sum += n; // unboxing: Integer → int

[Link]("Sum = " + sum); // prints Sum = 6

What’s happening under the hood

- Integer iObj = 42; is compiled to Integer iObj = [Link](42);. The JVM caches small
integer values (‑128 to 127), so repeated autoboxing of the same literal reuses the same Integer
instance.

- int iPrim = iObj; becomes int iPrim = [Link]();.

- When you add an int to a List<Integer>, the compiler inserts the appropriate [Link] call
(autoboxing). When you read the element and assign it to an int, it inserts intValue() (unboxing).

Wrapper classes, together with autoboxing/unboxing, let you write cleaner code while still
benefiting from the object‑oriented features of the Java collections framework and APIs that
expect objects. Just remember that autoboxing/unboxing adds a tiny overhead, so for
performance‑critical loops you may want to stick with primitives.

20. Describe the complete Life Cycle of an Applet. Detail the purpose of the four main methods
(init(), start(), stop(), and destroy()) and the order in which they are called.

Applet Life‑Cycle Overview

An applet runs inside a web browser (or an applet viewer) and goes through a well‑defined
sequence of states. The Java runtime calls a set of lifecycle methods on the applet instance in a
specific order. Below is the typical flow, followed by a brief description of each method.

1. Loading & Initialization

- The browser loads the applet class, creates an instance, and calls *init()*.

- This is where you set up resources that are needed for the applet’s operation (GUI
components, thread creation, parameter reading, etc.). The method is called once in the applet’s
lifetime.
2. Starting

- After init() finishes, the browser calls *start()*.

- start() is invoked when the applet becomes visible (e.g., the page is displayed) or when the
user returns to a page that was previously stopped. It typically starts any background processing
or animation that was paused in stop().

3. Stopping

- When the user leaves the page, minimizes the browser, or the applet is no longer visible, the
runtime calls *stop()*.

- stop() should pause threads, stop animations, or release resources that aren’t needed while the
applet is not visible. It may be called multiple times (e.g., each time the user navigates away and
back).

4. Destruction

- When the applet is being removed from memory (browser window closed, applet viewer shut
down, or the applet is garbage‑collected), the runtime invokes *destroy()*.

- destroy() performs final cleanup: releasing system resources, closing network connections,
saving state, etc. It is called once, after the last stop().

Summary of the method purposes

- *init()* – one‑time initialization; set up UI, read parameters, allocate long‑lived resources.

- *start()* – (re)start the applet’s execution; resume animations or background work when it
becomes visible.

- *stop()* – pause execution; free temporary resources while the applet is hidden.

- *destroy()* – final cleanup; release everything before the applet is discarded.

Typical call order

init() → start() → (running) → stop() → start() → stop() → … → destroy()

The exact number of start()/stop() cycles depends on how the user interacts with the page, but
init() and destroy() are each called exactly once.

21. Explain the Delegation Event Model used for event handling in Java. Describe the three essential
components: Event Source, Event Object, and Event Listener, and illustrate their interaction
with an example.

Delegation Event Model in Java

Java’s GUI frameworks (AWT, Swing, JavaFX) use a delegation model for handling events.
Instead of each component trying to handle its own events, an event source generates an event
object and passes it to registered event listeners. Listeners implement the appropriate interface and
define what should happen when the event occurs.
The three essential components

1. Event Source – the object that generates the event (e.g., a JButton, JTextField, Mouse). The
source maintains a list of listeners that are interested in its events and provides methods to register
(addXxxListener) and unregister listeners.

2. Event Object – an instance that carries information about the event (source, timestamp, mouse
coordinates, key code, etc.). All event obcts inherit from [Link].

3. Event Listener – an object that implements a listener interface (e.g., ActionListener,


MouseListener). The listener defines one or more callback methods that the source invokes when
the event occurs.

Interaction flow

1. Registration – The application creates a listener object and registers it with the source using
[Link](listener).

2. Event generation – When the user interacts (clicks a button, moves the mouse, etc.), the source
creates an event object and calls the appropriate method on each registered listener (e.g.,
[Link](event)).

3. Event handling – The listener’s callback method runs, performing whatever logic the
application requires.

Simple example (Swing button)

import [Link].*;

import [Link].*;

public class DelegationDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("Delegation Demo");

JButton button = new JButton("Click me");

// Event Source – the JButton

// Event Listener – an anonymous ActionListener

[Link](new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// Event Object – ActionEvent e

[Link]("Button pressed! Source: " + [Link]());


}

});

[Link](button);

[Link](200, 100);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

What’s happening

- Event Source: JButton – it knows how to generate an ActionEvent when the user clicks it.

- Event Listener: The anonymous inner class implementing ActionListener. Its actionPerformed
method is the callback.

- Event Object: ActionEvent e – it contains details such as the source component ([Link]()),
a timestamp, and any command string.

When the user clicks the button, Swing internally creates the ActionEvent, looks up all registered
`ActionListener`s, and calls actionPerformed on each, passing the event object. This clean
separation lets multiple listeners respond to the same event and keeps UI code modular.

22. What are Layout Managers in AWT? Explain the purpose of three commonly used layout
managers: FlowLayout, BorderLayout, and GridLayout, and describe how a programmer
chooses which one to use.

Layout managers in AWT (and Swing) are objects that arrange the child components of a
container according to a set of rules. Instead of hard‑coding absolute positions, you let the
manager decide where each component goes, which makes the UI resilient to different window
sizes, font metrics, and locales.

Three commonly used layout managers

1. FlowLayout

Purpose: Places components left‑to‑right, top‑to‑bottom, in the order they are added. When a row
runs out of horizontal space, it starts a new row.

Typical use: Simple toolbars, status bars, or any situation where you want a “wrap‑around” list of
components.

Key properties: Alignment (LEFT, CENTER, RIGHT), horizontal and vertical gaps.

2. BorderLayout
Purpose: Divides the container into five regions – NORTH, SOUTH, EAST, WEST, and
CENTER. Components added without a region go to CENTER. Each region can hold only one
component, but you can nest containers to get more complex arrangements.

Typical use: Main application windows where a menu or toolbar sits on top (NORTH), a status
bar on bottom (SOUTH), a navigation panel on the side (WEST/EAST), and the content area in
the middle (CENTER).

Key properties: Fixed regions, components stretch to fill the region.

3. GridLayout

Purpose: Arranges components in a rectangular grid of equal‑sized cells. You specify the number
of rows and columns; components are placed row‑by‑row, left‑to‑right.

Typical use: Forms where each label and field line up in columns, or any UI that needs a uniform
grid (e.g., a calculator keypad).

Key properties: Exact row × column count, all cells have the same size

How to choose the right layout manager

1. Consider the overall structure – If the UI has distinct top/bottom/side areas, start with
BorderLayout. If it’s a simple linear list that may wrap, FlowLayout is a good fit. For a table‑like,
equal‑sized grid, use GridLayout.

2. Think about resizing behavior – BorderLayout lets the center component take all remaining
space, while FlowLayout keeps components at their preferred size and wraps. GridLayout forces
every cell to the same size, which can be rigid but predictable.

3. Combine managers – Most real‑world windows are built by nesting containers, each with its
own layout. For example, a BorderLayout window can contain a FlowLayout toolbar in the
NORTH region and a GridLayout form in the CENTER.

4. Future flexibility – If you anticipate adding or removing components at runtime, choose a


manager that supports dynamic changes (e.g., FlowLayout or BorderLayout with add()/remove()).
GridLayout works best when the number of cells is known ahead of time.

In practice you start with the manager that most closely matches the visual pattern you need, then
adjust by nesting containers or switching to a more sophisticated manager (e.g., GridBagLayout
or third‑party libraries) if the layout becomes too constrained.

23 Why java is called truly. Object oriented? Explain the features of Java

Why Java is called truly object-oriented

Java is considered truly object-oriented because it adheres to the fundamental principles of OOP:

1. Encapsulation – Bundling data (attributes) and methods (behavior) that operate on the data
within a single unit (class). Access to the data is controlled through public methods, hiding
internal implementation.

2. Abstraction – Hides complex implementation details and exposes only the necessary parts of an
object. Abstract classes and interfaces enable this.
3. Inheritance – Classes can inherit properties and behavior from parent classes, promoting code
reuse and hierarchy.

4. Polymorphism – Methods can be overridden or overloaded, allowing objects to behave


differently depending on context (e.g., method overriding, interfaces).

Additionally, Java treats everything as an object (except primitives, but even they have wrapper
classes). All code is part of a class, and you interact with objects via methods, reinforcing the
OOP model.

Key features of Java

1. Platform independence – “Write once, run anywhere” via bytecode and the JVM.

2. Strongly typed – Compile‑time type checking reduces runtime errors.

3. Garbage collection – Automatic memory management.

4. Rich standard library – Extensive APIs for I/O, networking, collections, GUI (Swing, JavaFX),
concurrency, etc.

5. Exception handling – Built‑in support for catching and managing errors.

6. Multithreading – Built‑in language support for concurrent programming.

7. Security – Sandboxing, bytecode verification, and permissions model.

8. Dynamic loading – Classes are loaded on demand, and reflection allows dynamic inspection
and invocation.

These features, combined with its OOP foundation, make Java a versatile, robust, and widely used
language.

24 What is a class? Explain Constructor and its types in Java

Class

A class is a blueprint that defines the properties (fields) and behaviors (methods) of a set of
objects. Think of it as a template: you describe what an object of that type will look like and what
it can do, then you create instances (objects) from it.

Constructor

A constructor is a special method that runs when an object of the class is instantiated. Its job is to
initialise the object’s state. Constructors have the same name as the class and no return type (not
even void).

Types of constructors in Java

1. Default (no‑argument) constructor – supplied automatically if you don’t write any constructor.
It simply calls the superclass’s no‑arg constructor and leaves fields at their default values.
public class Person {

private String name;

// default constructor (implicit)

2. Parameterized constructor – takes one or more parameters to set initial values.

public class Person {

private String name;

public Person(String name) { [Link] = name; }

3. Copy constructor – creates a new object as a copy of another object of the same class. Java
doesn’t provide one automatically, but you can write it yourself.

public class Person {

private String name;

public Person(Person other) { [Link] = [Link]; }

4. Constructor overloading – you can define multiple constructors with different parameter lists,
giving callers several ways to instantiate the class.

public class Person {

private String name;

private int age;

public Person(String name) { this(name, 0); }

public Person(String name, int age) { [Link] = name; [Link] = age; }

5. Private constructor – prevents external instantiation; useful for utility classes or enforcing a
singleton pattern.

public class Utility {

private Utility() {} // cannot be instantiated

public static void help() { … }

}
Key points

- A constructor can call another constructor in the same class with this(...).

- It can call a superclass constructor with super(...); if you omit it, the compiler inserts super()
automatically.

- Constructors are not inherited, but a subclass can invoke any accessible constructor of its
superclass.

25 Write a program in java to find the factorial of a number entered by user?

import [Link];

public class Factorial {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter a non‑negative integer: ");

int n = [Link]();

long result = 1;

for (int i = 2; i <= n; i++) {

result *= i;

[Link]("Factorial of " + n + " is " + result);

[Link]();

Explanation

1. We read an integer n from the user.

2. We initialise result to 1.

3. A loop multiplies result by each integer from 2 up to n.

4. Finally, we print the computed factorial.

Note: For large n, the factorial quickly exceeds the range of long; you could use BigInteger
instead if you need arbitrary precision.
26 Explain with proper diagram the life cycle of an applet with example

Applet Life Cycle

The life cycle of an applet involves the following stages:

1. Initialization: The applet is loaded and initialized.

2. Start: The applet is started.

3. Stop: The applet is stopped.

4. Destroy: The applet is destroyed.

Here is a diagram illustrating the life cycle of an applet:

+---------------+

| Initialization |

+---------------+

+---------------+

| Start |

+-----

+---------------+

| Running |

+---------

+---------------+

| Stop |

+---------------+

+---------------+

| Destroy |

+---------------+
Example

Here is an example of an applet that demonstrates its life cycle:

import [Link];

import [Link];

public class LifeCycleApplet extends Applet {

@Override

public void init() {

[Link]("Applet initialized");

@Override

public void start() {

[Link]("Applet started");

@Override

public void stop() {

[Link]("Applet stopped");

@Override

public void destroy() {

[Link]("Applet destroyed");

@Override

public void paint(Graphics g) {

[Link]("Life Cycle Applet", 20, 20);

HTML Code
<applet code="[Link]" width="300" height="200">

</applet>

When you run this applet, you will see the following output:

Applet initialized

Applet started

Applet stopped

Applet started

Applet stopped

Applet destroyed

This demonstrates the life cycle of an applet, including initialization, start, stop, and destroy.

27 Write short notes on JVM

JVM (Java Virtual Machine)

The Java Virtual Machine (JVM) is a software program that runs Java bytecode on a computer. It is the
runtime environment for Java, providing a layer of abstraction between the Java program and the
underlying hardware and operating system.

Key Features of JVM:

1. Platform Independence: JVM allows Java programs to run on any platform that has a JVM, without
modification.

2. Memory Management: JVM manages memory allocation and deallocation for Java programs.

3. Security: JVM provides a sandboxed environment for Java programs to run, ensuring security and
preventing malicious code from accessing sensitive data.

4. Dynamic Loading: JVM loads classes and libraries dynamically, as they are needed.

Components of JVM:

1. Class Loader: Loads Java classes and libraries into memory.

2. Bytecode Verifier: Verifies the integrity of Java bytecode.

3. Runtime Data Areas: Provides memory for Java programs to run.

4. Execution Engine: Executes Java bytecode.

How JVM Works:

1. The Java compiler compiles Java source code into bytecode.


2. The JVM loads the bytecode into memory.

3. The JVM verifies the bytecode.

4. The JVM executes the bytecode.

Benefits of JVM:

1. Platform Independence: Write once, run anywhere.

2. Memory Management: Automatic memory management reduces memory leaks.

3. Security: Sandboxed environment ensures security.

4. Dynamic Loading: Efficient use of memory and resources.

28 What is String? How to creating Strings in Java.

String in Java

In Java, a String is an object that represents a sequence of characters. Strings are immutable,
meaning that once created, their contents cannot be modified.

Creating Strings in Java

There are several ways to create Strings in Java:

1. String Literal: Using double quotes ("").

String str = "Hello, World!";

2. new Keyword: Using the new keyword.

String str = new String("Hello, World!");

3. String Constructor: Using the String constructor.

char[] chars = {'H', 'e', 'l', 'l', 'o'};

String str = new String(chars);

4. String Concatenation: Using the + operator.

String str1 = "Hello, ";

String str2 = "World!";

String str = str1 + str2;

5. StringBuilder or StringBuffer: Using StringBuilder or StringBuffer classes.

StringBuilder sb = new StringBuilder();

[Link]("Hello, ");
[Link]("World!");

String str = [Link]();

Important Notes:

- String literals are stored in the String constant pool, which is a memory area that stores unique
String objects.

- Using the new keyword creates a new String object in memory, even if a String with the same
contents already exists.

- String concatenation using the + operator is converted to a StringBuilder or StringBuffer


operation by the compiler.

- StringBuilder is more efficient than StringBuffer for single-threaded operations, while


StringBuffer is more suitable for multi-threaded operations.

29 Write about Built-in Exceptions.

Built‑in Exceptions in Java

Java ships with a rich hierarchy of exception classes that cover the most common error situations. All of them
inherit from [Link], which splits into two branches

- *Error* – serious, usually unrecoverable problems (e.g., OutOfMemoryError, StackOverflowError). Your code
normally doesn’t catch these.

- *Exception* – conditions that a program can reasonably handle. It further divides into:

- Checked exceptions – must be declared or caught (IOException, SQLException, ClassNotFoundException, …).

- Unchecked (runtime) exceptions – do not need to be declared (NullPointerException,


ArrayIndexOutOfBoundsException, ArithmeticException, …)

Common Built‑in Exception Types

| Category | Example | Typical cause |

|----------|---------|---------------|

| Checked | IOException | I/O failures (file not found, network error) |

| | FileNotFoundException | Attempting to open a non‑existent file |

| | SQLException | Database access errors |

| | ClassNotFoundException | Unable to load a class at runtime |

| Unchecked | NullPointerException | Accessing a null reference |

| | ArrayIndexOutOfBoundsException | Invalid array index |

| | ArithmeticException | Illegal arithmetic operation (e.g., division by zero) |

| | IllegalArgumentException | Passing an illegal argument to a method |

| | NumberFormatException (subclass of IllegalArgumentException) | Converting a string to a numeric type fails |

| Error‑like | OutOfMemoryError | JVM runs out of heap space |


| | StackOverflowError | Too many nested method calls |

How They Are Used

- Checked exceptions force the caller to handle the error (try‑catch) or declare it with throws. This makes failure
handling explicit.

- Unchecked exceptions represent programming bugs; they usually propagate up the call stack until caught or the
JVM terminates.

Quick Example

import [Link].*;

public class Demo {

public static void main(String[] args) {

try {

readFile("[Link]");

} catch (FileNotFoundException e) {

[Link]("File not found: " + [Link]());

} catch (IOException e) {

[Link]("I/O error: " + [Link]());

static void readFile(String path) throws IOException {

BufferedReader br = new BufferedReader(new FileReader(path));

String line;

while ((line = [Link]()) != null) {

[Link](line);

[Link]();

In this snippet, FileNotFoundException (a checked exception) is caught explicitly, while IOException handles any
other I/O problems. Built‑in exceptions like these keep Java programs robust by providing a standard,
well‑documented way to signal and handle errors.

30 Write about zipping and unzipping files.

Zipping and Unzipping Files in Java

Java’s [Link] package gives you everything you need to create ZIP archives and extract
them again. The two most common classes are ZipOutputStream (for writing) and ZipInputStream
(for reading).
1. Creating a ZIP file (zipping)

import [Link].*;

import [Link].*;

public class ZipDemo {

public static void main(String[] args) {

String[] files = {"[Link]", "images/[Link]", "data/[Link]"};

String zipName = "[Link]";

try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName))) {

for (String f : files) {

File file = new File(f);

// Preserve the directory structure inside the zip

ZipEntry entry = new ZipEntry([Link]());

[Link](entry);

// Read the file and write it into the zip entry

try (FileInputStream fis = new FileInputStream(file)) {

byte[] buffer = new byte[1024];

int len;

while ((len = [Link](buffer)) > 0) {

[Link](buffer, 0, len);

[Link]();

[Link]("ZIP created: " + zipName);

} catch (IOException e) {

[Link]();

}
}

Key points

- ZipOutputStream wraps any OutputStream; we use a FileOutputStream to write to a file named


[Link].

- Each file gets a ZipEntry that holds its name (and optionally its path).

- The content is copied chunk‑by‑chunk to avoid loading the whole file into memory.

2. Extracting a ZIP file (unzipping)

import [Link].*;

import [Link].*;

public class UnzipDemo {

public static void main(String[] args) {

String zipName = "[Link]";

String destDir = "extracted";

try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipName))) {

ZipEntry entry;

while ((entry = [Link]()) != null) {

File outFile = new File(destDir, [Link]());

// Create parent directories if they don’t exist

if ([Link]()) {

[Link]();

continue;

[Link]().mkdirs();

// Write the file’s contents

try (FileOutputStream fos = new FileOutputStream(outFile)) {

byte[] buffer = new byte[1024];

int len;
while ((len = [Link](buffer)) > 0) {

[Link](buffer, 0, len);

[Link]("Extracted: " + [Link]());

} catch (IOException e) {

[Link]();

Key points

- ZipInputStream reads the archive entry by entry.

- getNextEntry() returns the next ZipEntry; when it’s a directory we just create it.

- For regular entries we stream the bytes to a FileOutputStream, recreating the original file
structure.

3. Quick notes

- Compression level: ZipOutputStream has a setLevel(int) method (0‑9). 9 gives maximum


compression, 0 means no compression.

- Other formats: For GZIP (single‑file) use GZIPOutputStream/GZIPInputStream. For the newer
ZIP‑64 (files > 4 GB) the same classes handle it automatically.

- Error handling: Always close streams in a finally block or use try‑with‑resources as shown.

That’s the essence of zipping and unzipping files in Java. You can drop the code into any project,
adjust the file lists or destinations, and you’re good to go.

31 Explain about local and remote applet.

Applets in Java

An applet is a small Java program that runs within a web browser or an applet viewer. Applets are typically used
for creating interactive web pages, games, and animations

Types of Applets

There are two types of applets:


1. Local Applet: A local applet is an applet that is stored on the local machine, i.e., the machine running the web
browser. The applet is loaded and executed by the browser without any network connection.

2. Remote Applet: A remote applet is an applet that is stored on a remote server, i.e., a machine other than the
one running the web browser. The applet is loaded and executed by the browser over a network connection.

Key Differences

| | Local Applet | Remote Applet |

| Location | Stored on local machine | Stored on remote server |

| Loading | Loaded directly by browser | Loaded over network connection |

| Security | Less secure, has access to local resources | More secure, runs in a sandboxed environment |

| Deployment | Easy to deploy, no network required | Requires network connection, more complex deployment

Local Applet Examplw

import [Link];

import [Link];

public class LocalApplet extends Applet {

@Override

public void paint(Graphics g) {

[Link]("Hello, World!", 20, 20);

HTML Code

<applet code="[Link]" width="200" height="100"></applet>

Remote Applet Example

import [Link];

import [Link];

public class RemoteApplet extends Applet {

@Override

public void paint(Graphics g) {

[Link]("Hello, World!", 20, 20);

HTML Code

<applet codebase="[Link] code="[Link]" width="200"


height="100"></applet>

Note: The codebase attribute specifies the URL of the remote server where the applet is located.

Security Considerations
Remote applets are subject to strict security restrictions, such as:

- No access to local file system

- No access to network resources

- Limited access to system resources

To overcome these restrictions, remote applets can be digitally signed, which grants them additional permissions.

32 What are the command line arguments? How they are use?

Applets in Java

An applet is a small Java program that runs within a web browser or an applet viewer. Applets are typically used
for creating interactive web pages, games, and animations.

Types of Applets

There are two types of applets:

1. Local Applet: A local applet is an applet that is stored on the local machine, i.e., the machine running the web
browser. The applet is loaded and executed by the browser without any network connection.

2. Remote Applet: A remote applet is an applet that is stored on a remote server, i.e., a machine other than the
one running the web browser. The applet is loaded and executed by the browser over a network connection.

Key Differences

| | Local Applet | Remote Applet |

| --- | --- | --- |

| Location | Stored on local machine | Stored on remote server |

| Loading | Loaded directly by browser | Loaded over network connection |

| Security | Less secure, has access to local resources | More secure, runs in a sandboxed environment |

| Deployment | Easy to deploy, no network required | Requires network connection, more complex deployment |

Local Applet Example

import [Link];

import [Link];

public class LocalApplet extends Applet {

@Override

public void paint(Graphics g) {

[Link]("Hello, World!", 20, 20);

HTML Code

<applet code="[Link]" width="200" height="100"></applet>

Remote Applet Example

import [Link];
import [Link]

public class RemoteApplet extends Applet {

@Override

public void paint(Graphics g) {

[Link]("Hello, World!", 20, 20);

HTML Code

<applet codebase="[Link] code="[Link]" width="200"


height="100"></applet>

Note: The codebase attribute specifies the URL of the remote server where the applet is located.

Security Considerations

Remote applets are subject to strict security restrictions, such as:

- No access to local file system

- No access to network resources

- Limited access to system resources

32 What are the command line arguments? How they are use?

Command Line Arguments in Java

Command line arguments are values passed to a Java program when it is executed from the command line. These
arguments are used to customize the behavior of the program or provide input data.

How to Use Command Line Arguments

In Java, command line arguments are passed to the main method as an array of String objects. The syntax is as
follows

public class MyProgram {

public static void main(String[] args) {

// args is an array of command line arguments

Example

Suppose we have a Java program called [Link]:

public class Greeting {

public static void main(String[] args) {

if ([Link] > 0) {

[Link]("Hello, " + args[0] + "!");

} else {
[Link]("Hello, World!");

To run this program with a command line argument, we would use the following command:

javac [Link]

java Greeting John

Output:

Hello, John!

In this example, John is the command line argument passed to the Greeting program.

Multiple Command Line Arguments

We can pass multiple command line arguments to a Java program by separating them with spaces:

public class Sum

public static void main(String[] args) {

int sum = 0;

for (String arg : args) {

sum += [Link](arg);

[Link]("Sum: " + sum);

To run this program with multiple command line arguments:

javac [Link]

java Sum 10 20 30

Output:

Sum: 60

In this example, 10, 20, and 30 are the command line arguments passed to the Sum program.

Common Use Cases

1. Configuration: Command line arguments can be used to configure the behavior of a program, such as specifying
a configuration file or setting a logging level.

2. Input data: Command line arguments can be used to provide input data to a program, such as file names or
data values.

3. Automation: Command line arguments can be used to automate tasks, such as running a program with specific
parameters or scheduling tasks.
[Link] are the different forms of Inheritance supported by Java?

Inheritance in Java

Java supports the following forms of inheritance:

1. Single Inheritance: A subclass inherits from a single superclass.

public class Animal {

// superclass

public class Dog extends Animal {

// subclass

2. Multilevel Inheritance: A subclass inherits from a superclass that itself inherits from another superclass.

public class Animal {

// superclass

public class Mammal extends Animal {

// subclass of Animal

public class Dog extends Mammal {

// subclass of Mammal

3. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.

public class Animal {

// superclass

public class Dog extends Animal {

// subclass 1

public class Cat extends Animal {

// subclass 2

4. Multiple Inheritance (through interfaces): A class can implement multiple interfaces, which allows for multiple
inheritance of behavior.

public interface Flyable {

void fly();
}

public interface Swimable {

void swim();

public class Duck implements Flyable, Swimable {

@Override

public void fly() {

// implementation

@Override

public void swim() {

// implementation

34 What is the difference between interface and Abstract class?

Interface vs Abstract Class in Java

Here are the main differences between an interface and an abstract class in Java:

Interface

1. Definition: An interface is a contract that specifies a set of methods that must be implemented by any class that
implements it.

2. Methods: Interfaces can only have abstract methods (no implementation) and default methods (Java 8+).

3. Variables: Interfaces can have only public, static, and final variables (i.e., constants).

4. Inheritance: A class can implement multiple interfaces.

5. Constructor: Interfaces cannot have constructors.

Abstract Class

1. Definition: An abstract class is a class that cannot be instantiated and is designed to be inherited by other
classes.

2. Methods: Abstract classes can have both abstract and concrete methods.

3. Variables: Abstract classes can have instance variables, which can be accessed by subclasses.

4. Inheritance: A class can extend only one abstract class.

5. Constructor: Abstract classes can have constructors, which are called by subclasses.
35 What are the features of Java? Explain.

Features of Java

Java is a popular programming language that has been widely used for developing a wide range of applications,
including Android apps, web applications, and enterprise software. Here are some of the key features of Java:

1. Object-Oriented: Java is an object-oriented language that supports encapsulation, inheritance, and


polymorphism.

2. Platform Independent: Java is platform independent, meaning that Java code can run on any device that has a
Java Virtual Machine (JVM) installed, regardless of the underlying operating system or hardware architecture.

3. Simple and Secure: Java is designed to be simple and secure, with features such as automatic memory
management, type checking, and a robust security model.

4. Robust and Reliable: Java is designed to be robust and reliable, with features such as exception handling,
garbage collection, and a strong focus on error checking and debugging.

5. Multithreaded: Java supports multithreading, which allows programs to execute multiple threads of execution
concurrently, improving responsiveness and performance.

6. Distributed: Java supports distributed programming, with features such as Remote Method Invocation (RMI)
and socket programming.

7. Dynamic: Java is a dynamic language that supports dynamic loading of classes, dynamic method invocation, and
other dynamic features.

8. Architecture Neutral: Java is architecture neutral, meaning that Java code can run on any device, regardless of
the underlying hardware architecture.

9. High Performance: Java has high performance, thanks to the Just-In-Time (JIT) compiler and other
optimizations.

10. Large Community: Java has a large and active community, with many libraries, frameworks, and tools
available.

36 Explain about various types of looping statements in Java program.

Looping statements in Java

Java gives you four ways to repeat a block of code:

1. *for loop* – best when you know the exact number of iterations.

for (int i = 0; i < 5; i++) {

[Link](i); // prints 0 … 4

2. *while loop* – runs as long as a condition is true; the test is checked before the body.

int x = 0;

while (x < 3) {

[Link](x++);

3. *do‑while loop* – like while, but the body executes once before the condition is evaluated.
int y = 0;

do {

[Link](y++);

} while (y < 2); // prints 0, 1

4. *Enhanced for (foreach)* – iterates over arrays or collections without an index.

int[] nums = {10, 20, 30};

for (int n : nums) {

[Link](n);

Control keywords you can use inside any loop

- break – exits the loop immediately.

- continue – skips the rest of the current iteration and jumps to the next one.

37 Explain how to create Objects and Accessing class members with example

Creating an object in Java is a two‑step process:

1. Declare a reference variable of the class type.

2. Instantiate the object with the new keyword, which also calls a constructor.

Once the object exists you can reach its fields (data) and methods (behaviour) with the dot (.) operator.

Example

// A simple class

public class Person {

// fields

String name;

int age;

// constructor

public Person(String n, int a) {

name = n;

age = a;

// method

public void greet() {

[Link]("Hi, I’m " + name + " and I’m " + age + " years old.");

// Another class that uses Person


public class Demo {

public static void main(String[] args) {

// declare a reference

Person p;

// create the object – the constructor runs

p = new Person("Ravi", 23);

// Accessing members

[Link]([Link]); // reads the field

[Link] = 24; // writes the field

[Link](); // calls the method

What’s happening

- Person p; just creates a variable that can hold a Person reference; no object exists yet.

- new Person("Ravi", 23) allocates memory for a Person instance, runs the constructor to initialise name and age,
and returns a reference to that new object.

- [Link] and [Link] let you read or modify the object's data.

- [Link]() invokes the method defined in the class.

38 Explain about methods in Java wit example.

Methods in Java

A method is a block of code that performs a specific task. It can be called (invoked) from other parts of the
program, optionally receiving data (parameters) and optionally returning a value.

Key parts of a method declaration

1. Access modifier – public, protected, private or default (package‑private).

2. Return type – the data type the method gives back (int, double, String, void for no return).

3. Method name – follows camel‑case convention.

4. Parameter list – comma‑separated types and names inside parentheses (may be empty).

5. Body – the code that runs when the method is called, enclosed in {}.

Example

public class Calculator {

// instance method – needs an object to be called

public int add(int a, int b) {

return a + b;

}
// static method – can be called without an object

public static double average(double[] numbers) {

double sum = 0;

for (double n : numbers) {

sum += n;

return sum / [Link];

// method overloading – same name, different parameters

public int multiply(int a, int b) {

return a * b;

public int multiply(int a, int b, int c) {

return a * b * c;

Using the methods

public class Demo {

public static void main(String[] args) {

Calculator calc = new Calculator();

int sum = [Link](5, 7); // instance method

[Link]("5 + 7 = " + sum)

double[] vals = {10, 20, 30};

double avg = [Link](vals); // static method

[Link]("Average = " + avg);

[Link]("2 * 3 = " + [Link](2, 3));

[Link]("2 * 3 * 4 = " + [Link](2, 3, 4));

39 What is Java? Explain JDK, JRE and JVM

What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by
Oracle Corporation) in the mid-1990s. Java is designed to be platform-independent, allowing Java programs to run
on any device that has a Java Virtual Machine (JVM) installed, regardless of the underlying operating system or
hardware architecture.
Java Buzzwords

1. Write Once, Run Anywhere (WORA): Java's platform independence allows code to run on any device, regardless
of the underlying operating system or hardware architecture.

2. Object-Oriented: Java is an object-oriented language that supports encapsulation, inheritance, and


polymorphism.

3. Simple and Secure: Java is designed to be simple and secure, with features such as automatic memory
management, type checking, and a robust security model.

JDK, JRE, and JVM

1. JDK (Java Development Kit): The JDK is a software development kit that includes everything you need to
develop, test, and run Java applications. It includes:

- Java compiler (javac)

- Java Runtime Environment (JRE)

- Java libraries and APIs

- Development tools (e.g., jdb, jconsole)

2. JRE (Java Runtime Environment): The JRE is a software package that provides the runtime environment for Java
applications. It includes:

- Java Virtual Machine (JVM)

- Java libraries and APIs

- Java plugins for web browsers

3. JVM (Java Virtual Machine): The JVM is a software program that runs Java bytecode (compiled Java code) on a
computer. It translates bytecode into machine-specific code at runtime, allowing Java programs to run on any
device with a JVM, regardless of the underlying operating system or hardware architecture.

How they work together

1. You write Java code using a text editor or IDE.

2. You compile the Java code using the JDK's Java compiler (javac), which generates bytecode.

3. The bytecode is run on the JRE, which includes the JVM.

4. The JVM translates the bytecode into machine-specific code at runtime, allowing the Java program to run on
the underlying operating system and hardware architecture.

40 Briefly explain about different types of packages..

Java packages are used to organize related classes and interfaces. Here are the main types:

1. Built-in Packages: These are pre-defined packages that come with the Java Development Kit (JDK). Examples
include:

- [Link]: Fundamental classes (e.g., String, System)

- [Link]: Utility classes (e.g., ArrayList, HashMap)

- [Link]: Input/output classes (e.g., File, BufferedReader)

2. User-defined Packages: These are custom packages created by developers to organize their own classes and
interfaces.
3. Imported Packages: These are packages that are imported from other libraries or projects, making their classes
and interfaces available for use.

Package Structure

- [Link]: A typical package name, with com being the top-level domain, example being the
organization, and myapp being the application name.

- java and javax are reserved for Java standard libraries.

41 Explain the life cycle of an applet with neat diagram.

Applet Life Cycle

An applet goes through several stages during its lifetime, which are managed by the Applet container (usually a
web browser). the life cycle of an applet is as follows:

1. Initialization (init()): The applet is loaded and initialized.

2. Start (start()): The applet is started or restarted.

3. Running (paint()): The applet is running and displaying its UI.

4. Stop (stop()): The applet is stopped, usually when the user navigates away from the page.

5. Destroy (destroy()): The applet is unloaded and destroyed.

Diagram

| Initialization |

| (init()) |

| Start |

| (start())

| Running |

| (paint())

| Stop |

| (stop())

| Destroy |

| (destroy())

Explanation

1. Initialization (init()): The applet is loaded and initialized. This is where you perform one-time setup tasks, such
as loading resources or initializing variables.

2. Start (start()): The applet is started or restarted. This is where you start any threads or animations.
3. Running (paint()): The applet is running and displaying its UI. This is where you handle user input and update
the display.

4. Stop (stop()): The applet is stopped, usually when the user navigates away from the page. This is where you
stop any threads or animations.

5. Destroy (destroy()): The applet is unloaded and destroyed. This is where you release any system resources, such
as memory or graphics contexts.

42 What are the difference between while loop and do-while loop. Write a program using 'While Loop' for /

factorial of a number.

While vs. Do‑while

A while loop checks the condition first; if it’s false the body never runs.

A do‑while loop executes the body once and only then checks the condition, so the body always runs at least one
time

Factorial using a while loop (Java)

import [Link];

public class Factorial {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a non‑negative integer: ");

int n = [Link]();

long fact = 1;

int i = 1;

while (i <= n) {

fact *= i;

i++;

[Link]("Factorial of " + n + " is " + fact);

[Link]();

43 Explain constructor and destructor with suitable example.

Constructor

A constructor is a special method that runs automatically when an object is created.

Its job is to initialise the object’s fields.

- name must match the class name

- has no return type (not even void)


- can be overloaded – you can have several constructors with different parameter lists

Destructor (Java’s view)

Java does not have true destructors like C++. Objects are reclaimed by the garbage collector.

If you need to release resources (files, sockets, etc.) you can implement the finalize() method – it is called once by
the GC before the object is discarded, but you cannot rely on it running at a specific time.

Example

public class Person {

private String name;

private int age;

// No‑argument constructor

public Person() {

[Link] = "Unknown";

[Link] = 0;

// Parameterised constructor

public Person(String name, int age) {

[Link] = name;

[Link] = age;

// Copy constructor (creates a duplicate)

public Person(Person other) {

[Link] = [Link];

[Link] = [Link];

// Destructor‑like method (called by GC)

@Override

protected void finalize() throws Throwable {

[Link]("Person object for " + name + " is being garbage‑collected");

// release any native resources here

[Link]();

@Override

public String toString() {

return "Person{name='" + name + "', age=" + age + '}';


}

// Simple test

public static void main(String[] args) {

Person p1 = new Person("Alice", 30);

Person p2 = new Person(p1); // copy constructor

Person p3 = new Person(); // no‑arg constructor

[Link](p1);

[Link](p2);

[Link](p3);

// make objects eligible for GC

p1 = p2 = p3 = null;

[Link](); // request GC (just for demo)

44. What is Inheritance? What type of Inheritance does Java support?

Inheritance is a core OOP concept where one class (the subclass or child) acquires the fields and methods of
another class (the superclass or parent). The subclass can reuse that behavior, add new members, or override
existing ones, which helps you write less duplicate code and model real‑world “is‑a” relationships.

How Java handles inheritance

- Single inheritance for classes – a class can extend at most one other class.

class Animal { … }

class Dog extends Animal { … } // Dog inherits from Animal only

- Multilevel inheritance – a chain of subclasses: Animal → Mammal → Dog. Each link inherits from the one above
it.

- Hierarchical inheritance – many subclasses share the same superclass: Animal is the parent of Dog, Cat, Bird, etc.

- Multiple inheritance of types – Java doesn’t let a class extend two classes, but a class can implement any number
of interfaces, giving you multiple inheritance of type (and, with default methods, even behavior).

interface Flyer { void fly(); }

interface Swimmer { void swim(); }

class Duck implements Flyer, Swimmer { … } // Duck gets both contracts

45. What is a thread? What is the difference between a process and a thread?

Thread

A thread is the smallest unit of execution within a process. It has its own call stack and can run independently,
sharing the process’s memory and resources. Think of it as a worker bee: multiple threads (bees) can work in
parallel within the same hive (process).
Process vs. Thread

| Aspect | Process | Thread |

|-------------------|-------------------------------------------------|---------------------------------------|

| Definition | An independent program with its own memory | A lightweight sub‑task within a process |

| Memory | Has its own separate memory space | Shares memory with other threads |

| Communication | Processes need inter‑process communication (IPC) | Threads can access shared data
directly |

| Creation | Heavyweight (OS overhead) | Lightweight (faster to create) |

| Failure | Crash of one process doesn’t affect others | Crash of one thread can crash the whole process |

Java’s take

Java supports multithreading. You can create threads by extending Thread or implementing Runnable. Threads
share the JVM’s heap but have their own stack, making them great for concurrent tasks like UI updates and
background processing.

46 What is an applet in Java? Explain with example.

Applet — what it is

An applet is a small Java program that runs inside a web browser (or a viewer) rather than as a stand‑alone
application. The browser loads the applet’s .class file, creates an instance of the applet class, and drives its
life‑cycle methods (init(), start(), paint(), stop(), destroy()). Because the applet lives in the browser’s JVM, it can’t
access the local file system directly and runs in a sandboxed security environment.

Simple example

import [Link];

import [Link];

public class HelloApplet extends Applet {

private String message = "Hello, applet!";

// Called once when the applet is loaded

public void init() {

message = getParameter("msg"); // read <param name="msg" value="...">

// Called when the applet becomes visible

public void start() {

// start any threads, animations, etc.

// Draws the applet’s UI

public void paint(Graphics g) {

[Link](message, 50, 50);

}
// Called when the page is left

public void stop() {

// stop threads, pause animation

// Called when the applet is being unloaded

public void destroy() {

// release resources

47 Write short notes on any two of the following:

(a) Method overloading

(b) Event

(c) Class and object

(d) TCP/IP

Method Overloading

Method overloading is a feature in Java where multiple methods can have the same name but with different
parameter lists. The compiler determines which method to call based on the number and types of arguments
passed.

Example:

public class Calculator {

public int add(int a, int b) { return a + b; }

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

public int add(int a, int b, int c) { return a + b + c; }

Event

An event is a notification sent by an object when something happens that other objects might need to know
about. Events are commonly used in GUI programming to handle user interactions like clicks, key presses, etc.

Example:

public class Button {

public void addActionListener(ActionListener listener) {

// add listener

public void click() {

// trigger event

}
}

Class and Object

- Class: A blueprint or template that defines properties and behaviors.

- Object: An instance of a class, with its own set of attributes and methods.

Example:

public class Car {

String color;

int speed;

public Car(String color, int speed) {

[Link] = color;

[Link] = speed;

public void drive() {

[Link]("Driving...");

Car myCar = new Car("Red", 120);

[Link](); // Output: Driving...

TCP/IP

TCP/IP (Transmission Control Protocol/Internet Protocol) is a set of rules governing how data is transmitted over
the internet. It ensures reliable communication between devices.

Key features:

- Connection-oriented (TCP)

- Packet switching

- Error detection and correction

48 what is the primary advantage of java being platform independent

Java’s “write once, run anywhere” promise means you compile your code into bytecode once, and the JVM takes
care of translating that bytecode into the native instructions of any OS or hardware it runs on. So the primary
advantage is portability – you don’t have to rewrite or recompile your program for Windows, Linux, macOS,
Android, etc.; a single build works everywhere that has a JVM. This saves development time, reduces
maintenance effort, and lets your application reach a broader audience without extra work.

49. what is a common disadvantage of java architecture in terms of performance compared to native language like
c++

One big downside is that Java runs on a virtual machine, so every operation carries extra overhead—bytecode
interpretation, JIT compilation, and garbage‑collection pauses. Compared with a native language like C++, which
compiles straight to machine code and lets you manage memory manually, Java typically ends up slower and uses
more memory, especially for latency‑sensitive tasks.

50. What is the advantage of using dynamic initialization for variables, such as initializing a variable based on a
method call?

Dynamic initialization lets you set a variable’s value at the moment it’s created, using whatever logic you need—
such as the result of a method call, a calculation, or data read from a file. The main advantages are:

1. Readability – the initialization is written right where the variable is declared, so you don’t have to hunt through
the code for the first assignment.

2. Safety – the variable is guaranteed to have a meaningful value as soon as it exists, reducing the chance of using
an uninitialized or default value by mistake.

3. Encapsulation – complex setup (e.g., calling a helper method) stays close to the variable, keeping the
surrounding code cleaner.

4. Concurrency‑friendly – if the variable is final, dynamic initialization ensures it can’t be changed later, which
helps avoid race conditions in multithreaded contexts.

51. Are there any disadvantages to using dynamic initialization in a performance-critical loop? Explain briefly.

Dynamic initialization inside a tight loop can hurt performance because every iteration has to execute whatever
code you put in the initializer—method calls, object creation, I/O, etc. That adds overhead that a simple
assignment would avoid. In a performance‑critical loop you usually want the body to be as cheap as possible, so
it’s better to hoist the initialization out of the loop or reuse a pre‑computed value. Otherwise you may see extra
CPU cycles, more garbage‑collection pressure, and reduced ability for the JIT to optimize the loop.

52. What is the primary advantage for a developer when using Java's built-in Garbage Collection?

Java’s garbage collector takes care of reclaiming memory that your objects no longer need, so you don’t have to
write explicit free or delete calls. This eliminates a whole class of bugs—memory leaks, double‑frees, and dangling
pointers—and lets you focus on the problem you’re solving instead of tracking every allocation. In short, it makes
development faster, safer, and less error‑prone.

53. What potential disadvantage can occur in a Java application if the Garbage Collector runs at an unpredictable
time, especially in real-time systems?

The Garbage Collector (GC) in Java can introduce unpredictable pauses, which can be problematic for real-time
systems that need consistent, low-latency responses. When the GC decides to run, it might freeze the entire
application briefly to clean up memory, causing delays that are hard to anticipate. This can lead to missed
deadlines, jitter, or even crashes if the system expects faster reactions.

Java has some GC algorithms (like G1, ZGC, or Shenandoah) designed to minimize these pauses, but for ultra-low-
latency or hard real-time apps, you might still need more control over memory management (e.g., off-heap
storage, native memory, or tuning GC parameters).

54. What is the main advantage of declaring a method or variable as static in a class?

Declaring a method or variable static means it belongs to the class itself rather than to any particular instance.
The big win is that you can access it without creating an object—just [Link]. This is handy for utility
functions, constants, or shared data that should be the same for every object, saving memory and making the
intent clear.
55. What is a potential disadvantage or risk associated with the overuse of static variables in a multi-threaded
application?

Overusing static variables in a multith‑threaded program creates a shared mutable state that every thread can
read and write. That leads to two big problems:

1. Race conditions – if two threads modify the same static field at the same time without proper synchronization,
the data can become corrupted or behave unpredictably.

2. Hidden dependencies – static data is effectively global, so it’s hard to see which parts of the code rely on it. This
makes the program harder to test, debug, and maintain, and it can cause subtle bugs when the order of thread
execution changes.

In short, too many static variables undermine thread safety and modularity, turning what should be isolated
pieces of logic into a tangled, error‑prone mess. Proper synchronization or redesigning the data into thread‑local
or instance‑level variables is usually a better route.

56. What is a potential disadvantage or limitation of Java's design choice to support only single inheritance?

Java’s single‑inheritance model means a class can extend only one parent, which can force you to duplicate code
or resort to interfaces and composition to share behavior from multiple sources. This can make the class hierarchy
less flexible and sometimes leads to “diamond‑inheritance” work‑arounds that are less intuitive than true
multiple inheritance.

57. What is a key advantage of using Interfaces over an abstract class in Java for achieving "multiple inheritance"
of type?

Using an interface lets a class “inherit” from multiple types at once—something an abstract class can’t do because
Java only allows single inheritance of implementation. That means you can give a class several distinct contracts
(behaviors) without forcing it into a single‑inheritance chain, which keeps the design flexible and avoids the
“diamond‑inheritance” problems that multiple inheritance can cause.

In short: interfaces give you multiple‑type inheritance while keeping the class hierarchy simple and loosely
coupled.

58. What is a disadvantage of using interfaces regarding state, specifically in terms of instance fields (variables)?

Interfaces can't have instance fields (non‑static variables), so you can’t store state in them—only constants
(implicitly public static final) and method signatures. If you need shared state, you have to resort to other
mechanisms, like abstract classes, composition, or external state management, which can make the design less
straightforward.

59. How do Packages provide an advantage for managing a large codebase and avoiding naming conflicts?

Packages group related classes and interfaces into a unique namespace, so you can have the same class name in
different packages without collisions. This lets you organize code logically (e.g., [Link],
[Link]) and import only what you need, making the codebase more modular and avoiding naming
conflicts when using external libraries.

60. What is a potential disadvantage if a developer doesn't properly manage the classpath when working with
custom packages?

If the classpath isn’t set up correctly for your custom packages, the JVM can’t locate the compiled .class files, so
you’ll get ClassNotFoundException or NoClassDefFoundError at runtime. It also makes it easy to accidentally pick
up the wrong version of a class (e.g., an older build) because the class loader will search the classpath in order. In
short, a sloppy classpath leads to missing classes, unexpected behavior, and a lot of “why isn’t this working?”
headaches.
61. What is the main advantage of Dynamic Method Dispatch in promoting flexible and maintainable code?

Dynamic Method Dispatch (polymorphism) lets you call overridden methods on a superclass reference, and the
actual method that runs is determined at runtime based on the object’s true type. This means you can write code
that works with the abstract superclass, and subclasses can provide their own behavior without changing the
calling code. It promotes loose coupling, makes it easy to add new subclasses, and keeps the code open for
extension but closed for modification (Open/Closed Principle).

62. Can there be a minor disadvantage to Dynamic Method Dispatch in terms of runtime overhead compared to
static binding? Briefly explain.

Dynamic Method Dispatch (DMD) is slightly slower than static binding because the JVM has to resolve the actual
method to call at runtime, using the object’s vtable (virtual method table). This extra lookup adds a tiny bit of
overhead compared to static (compile‑time) binding, but modern JVMs optimize this heavily, so the cost is usually
negligible unless you’re in a super‑tight loop.

63. What is the core advantage of implementing structured Exception Handling (using try-catch)?

Exception handling (try‑catch) lets you separate the happy path (normal flow) from error handling, so your main
logic stays clean and readable. It also gives you a chance to recover gracefully, log issues, or provide fallback
behavior when something goes wrong, rather than crashing the program. This makes apps more robust and
user‑friendly.

64. What is a disadvantage of "catching" theException class base instead of catching specific exception
subclasses?

Catching the base Exception (or even Throwable) can hide bugs:

- Swallows unexpected errors – you end up handling things like NullPointerException, OutOfMemoryError, or
other programming mistakes as if they were normal, recoverable conditions.

- Makes debugging harder – the original cause gets lost, so you won’t see the stack trace or know which line
failed.

- Can mask library‑level issues – a library might throw a new, unforeseen subclass; you’ll catch it unintentionally,
possibly breaking the library’s intended error‑handling contract.

In short, catching specific subclasses keeps your error handling precise and lets you react appropriately to each
failure mode.

65. When performing many modifications to a string (e.g., in a loop), what is the clear advantage of using
StringBuffer over String?

Using StringBuffer lets you modify a string in place, so each append or insert updates the same internal buffer
instead of creating a brand‑new String object every time. In a loop this eliminates a ton of temporary objects, cuts
memory churn, and can be noticeably faster—especially for large or many‑iteration workloads. (If you don’t need
thread‑safety, StringBuilder gives the same benefit with less synchronization overhead.)

You might also like