0% found this document useful (0 votes)
10 views29 pages

Java 23

The document provides an overview of key concepts in Java, including constructors, method overloading, access specifiers, inheritance, polymorphism, and user-defined exceptions. It explains the rules and types of constructors, the principles of method overloading and polymorphism, and the use of the super keyword. Additionally, it contrasts abstract classes and interfaces, detailing how to implement interfaces and achieve multiple inheritance through them.

Uploaded by

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

Java 23

The document provides an overview of key concepts in Java, including constructors, method overloading, access specifiers, inheritance, polymorphism, and user-defined exceptions. It explains the rules and types of constructors, the principles of method overloading and polymorphism, and the use of the super keyword. Additionally, it contrasts abstract classes and interfaces, detailing how to implement interfaces and achieve multiple inheritance through them.

Uploaded by

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

UNIT 2

2. Define Constructors. Classify the types of Constructors with


examples.

A Constructor in Java is a special type of method used to initialize an


object when it is created. It ensures that the newly created object starts in
a valid, predefined state.

Key Rules for Constructors:

 The constructor name must be the same as the class name.

 It has no explicit return type (not even void).

 It is implicitly invoked when the new keyword is used.

 It cannot be declared as static, abstract, final, or synchronized.

Types of Constructors

Type Description Example

If a class does not define any


constructor, the Java compiler Car c = new
Default automatically provides a public, no- Car(); (If Car has
Constructor argument constructor. It initializes no defined
instance variables to their default values constructor)
(e.g., 0 for numbers, null for objects).

A constructor explicitly defined by the


java Car()
programmer that takes no parameters.
No-Argument { model =
It is used to initialize all objects of that
Constructor "Unknown"; year
class with a fixed, predetermined set of
= 2025; }
values.

A constructor that accepts one or more


java Car(String
parameters. It allows the object's
Parameterize m, int y)
instance variables to be initialized with
d Constructor { model = m;
values passed during object creation,
year = y; }
enabling the creation of distinct objects.

Example of Constructor Overloading (demonstrating No-Arg and


Parameterized):

Java

class Student {

String name;
int id;

// 1. No-Argument (Default-like) Constructor

Student() {

[Link] = "Guest";

[Link] = 0;

// 2. Parameterized Constructor

Student(String name, int id) {

[Link] = name;

[Link] = id;

4. Explain Method Overloading with suitable examples.

Method Overloading (also known as Compile-time Polymorphism or


Static Polymorphism) is a feature that allows a class to have multiple
methods with the same name, provided their parameter lists are
different.

The compiler determines which method to call based on the number


and/or type of arguments passed.

Rules for Method Overloading

Methods are overloaded if they satisfy all the following conditions:

1. They must have the same method name.

2. They must have a different parameter list (different number of


arguments OR different data types of arguments OR different order
of data types).

3. The return type can be the same or different, but a change in the
return type alone is not sufficient for overloading.

Example
Java

class Calculator {

// 1. Overloaded method: sum(int, int)

public int sum(int a, int b) {

return a + b;

// 2. Overloaded method: sum(int, int, int) - Different number of


parameters

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

return a + b + c;

// 3. Overloaded method: sum(double, double) - Different data types

public double sum(double a, double b) {

return a + b;

class Main {

public static void main(String[] args) {

Calculator c = new Calculator();

[Link]([Link](5, 10)); // Calls method 1: sum(int,


int)

[Link]([Link](5, 10, 15)); // Calls method 2: sum(int,


int, int)

[Link]([Link](5.5, 10.5)); // Calls method 3:


sum(double, double)

}
6. Write a brief note on Access Controls or Access Specifiers in
Java.

Access Modifiers (or Access Specifiers) are keywords in Java that set the
accessibility (or visibility) of classes, interfaces, constructors, methods,
and instance variables. They are a core mechanism for implementing
Encapsulation and providing controlled access to members.

Java has four types of access levels:

Outside
Outside
Within Within Package
Modifier Access Level Package
Class Package (Any
(Subclass)
Class)

private Most Restrictive Yes No No No

default
(No Package-Private Yes Yes No No
keyword)

Inheritance/
protected Yes Yes Yes No
Package

public Least Restrictive Yes Yes Yes Yes

Modifier Where to Use Purpose

Fields, Methods, Hides data and helper methods; strictly


private
Constructors enforces encapsulation.

Classes, Fields, Default visibility; used for implementation


default Methods, details shared only within the same logical
Constructors group (package).

Allows inheritance-based access, often


protect Fields, Methods,
used for methods intended to be
ed Constructors
overridden by subclasses.

Classes, Fields, Exposes functionality to the entire


public Methods, application; used for the public API of a
Constructors class.

8. Define Inheritance. Explain the forms of Inheritance supported


by Java.
Definition of Inheritance

Inheritance is one of the fundamental concepts of Object-Oriented


Programming (OOP) where a new class (subclass or child class) is
created by inheriting the properties (fields) and behavior (methods) of an
existing class (superclass or parent class).

 It promotes Code Reusability.

 It establishes the IS-A relationship (e.g., a Dog IS-A Animal).

 It is achieved using the extends keyword.

Forms of Inheritance Supported by Java (via Classes)

Java supports the following three forms of inheritance through classes:

1. Single Inheritance: A class inherits from only one direct


superclass. This is the simplest and most common form.

o Example: Class B extends Class A.

2. Multilevel Inheritance: A class inherits from a class which, in turn,


inherits from another class. A chain of inheritance is formed.

o Example: Class C extends Class B, and Class B extends Class


A. (A $\rightarrow$ B $\rightarrow$ C)

3. Hierarchical Inheritance: Multiple classes inherit from a single


superclass.

o Example: Class B extends Class A, and Class C extends Class


A.

Unsupported Form

 Multiple Inheritance (via Classes): Java does not support


multiple inheritance of implementation (a class cannot directly
extend two or more classes) to avoid the Deadly Diamond of
Death ambiguity problem. This concept is achieved in Java through
Interfaces.

11. Write a brief note on the use of the super keyword in Java.

The super keyword is a reference variable used inside a subclass to refer


to the immediate superclass (parent class) object. It is crucial in
inheritance for resolving ambiguity and ensuring proper initialization.

The super keyword has three primary uses:


1. To Access Superclass Variables: Used when a subclass has an
instance variable with the same name as a variable in the
superclass (shadowing).

o Syntax: [Link]

Java

class Parent { int x = 10; }

class Child extends Parent {

int x = 20;

void display() {

[Link](super.x); // Accesses Parent's x (10)

2. To Invoke Superclass Methods: Used to call an overridden


method of the superclass from within the subclass. This allows the
subclass to extend or enhance the parent's behavior rather than
completely replacing it.

o Syntax: [Link]()

Java

class Parent { void show() { /* ... */ } }

class Child extends Parent {

@Override

void show() {

[Link](); // Calls Parent's show() method

// ... then add Child-specific logic

3. To Invoke Superclass Constructors: Used to call a specific


constructor of the superclass from the subclass constructor. This
ensures that the superclass's state is correctly initialized before the
subclass is initialized.

o Syntax: super(arguments)
o Rule: super() or super(args) must be the first statement in
the subclass constructor.

Java

class Parent { Parent(int i) { /* ... */ } }

class Child extends Parent {

Child(int i, int j) {

super(i); // Calls the one-argument constructor of Parent

// ... Child-specific initialization

15. Write about Polymorphism in Java.

Polymorphism is a fundamental principle of OOP that means "many


forms." It allows a single entity (like a method, or an object reference) to
exhibit different behaviors depending on the context.

In Java, polymorphism is primarily achieved in two ways:

1. Compile-time Polymorphism (Static Binding)

o Mechanism: Method Overloading (covered in question 4).

o Resolution: The specific method to be called is decided by


the compiler based on the method signature (name, number,
and type of parameters) at compile time.

2. Runtime Polymorphism (Dynamic Binding)

o Mechanism: Method Overriding and Dynamic Method


Dispatch.

o Resolution: The specific method to be called is decided by


the JVM at runtime based on the actual type of the object
being referred to, not the type of the reference variable.

Key Example (Runtime Polymorphism):

Java

class Animal {

void sound() { [Link]("Animal makes a sound."); }

}
class Dog extends Animal {

@Override

void sound() { [Link]("Dog barks."); }

class Main {

public static void main(String[] args) {

Animal myAnimal = new Dog(); // Superclass reference, Subclass


object

[Link](); // Output: Dog barks. (The actual object


type determines the method)

18. Briefly explain Dynamic Polymorphism in Java.

Dynamic Polymorphism (also known as Runtime Polymorphism or


Dynamic Method Dispatch) is the mechanism where the call to an
overridden method is resolved at runtime rather than at compile time.

Core Concepts

1. Method Overriding: A subclass provides a specific implementation


for a method that is already defined in its superclass.

2. Upcasting: A superclass reference variable is used to hold a


reference to a subclass object. This is the essential condition for
dynamic polymorphism to occur.

o Syntax: SuperClass ref = new SubClass();

3. Dynamic Method Dispatch: When the overridden method is


called using the superclass reference, the JVM looks at the actual
object type (the subclass type) at runtime to decide which version
of the method (superclass or subclass) to execute.

Working

The type of the reference variable (Animal in the example below)


determines what methods can be called, but the type of the actual
object (Dog) determines which version of the overridden method is
executed.

Example:

Java

class Vehicle {

void run() { [Link]("Vehicle is running."); }

class Bike extends Vehicle {

@Override

void run() { [Link]("Bike is riding."); } // Overridden method

class Test {

public static void main(String[] args) {

Vehicle v = new Bike(); // Upcasting: Vehicle reference, Bike object

[Link](); // Dynamic dispatch calls Bike's run() at runtime.

// Output: Bike is riding.

20. How to create User Defined Exceptions (Custom Exceptions) in


Java?

User-Defined Exceptions (or Custom Exceptions) allow a programmer


to create a new exception class tailored to the specific needs or business
rules of an application. This improves code readability and helps callers
handle specific, application-level errors distinctly.

Steps to Create a Custom Exception

1. Define a New Class: Create a new class that extends one of Java's
built-in exception classes:

o Extend Exception to create a Checked Exception (caller


must handle or declare it).
o Extend RuntimeException to create an Unchecked
Exception (caller is not required to handle it).

2. Define Constructors: Typically, define two constructors: a default


one and one that accepts a String message, passing it to the
superclass constructor via super().

Example (Creating a Checked Custom Exception)

Java

// 1. Define the custom exception (Checked Exception)

class InsufficientFundsException extends Exception {

// 2. Constructor to pass a message to the superclass

public InsufficientFundsException(String message) {

super(message);

// 3. Class using the exception

class Account {

private double balance = 1000.00;

public void withdraw(double amount) throws InsufficientFundsException


{

if (balance < amount) {

// 4. Throw the custom exception

throw new InsufficientFundsException("Withdrawal amount of " +


amount +

" exceeds current balance of " + balance);

balance -= amount;

[Link]("Withdrawal successful. Remaining balance: " +


balance);

}
}

// 5. Handling the exception

class Main {

public static void main(String[] args) {

Account acc = new Account();

try {

[Link](1500.00);

} catch (InsufficientFundsException e) {

[Link]("Transaction Failed! " + [Link]());

}
UNIT 3

1. Difference between Abstract Class and Interface

Feature Abstract Class Interface

Type Class Blueprint of a class/Contract

All methods are implicitly public


Can have abstract
abstract (in Java 7 and earlier).
(without body) and
Methods Can have default and static
concrete (with
methods from Java 8, and
body) methods.
private methods from Java 9.

Can have instance,


Variables are implicitly public
Variables static, and final
static final.
variables.

Can have
Constructo constructors (used
Cannot have constructors.
r by subclasses via
super()).

A class extends A class implements multiple


Inheritanc
only one abstract interfaces (achieving multiple
e
class. inheritance of type/contract).

Access Members can be Members are implicitly public.


Feature Abstract Class Interface

public, protected,
Modifiers
private, or default.

3. How to implement an interface? Explain with example?

An interface is implemented by a class using the implements keyword.


The implementing class must provide a concrete definition (body) for all
the abstract methods declared in the interface, or it must itself be
declared as abstract.

Example:

Java

// Define the Interface

interface Drivable {

// Abstract method (implicitly public abstract)

void startEngine();

void stopEngine();

// Implement the Interface

class Car implements Drivable {

@Override

public void startEngine() {

[Link]("Car engine started. Ready to drive.");

@Override

public void stopEngine() {

[Link]("Car engine stopped. Parking brake set.");

}
public void playMusic() {

[Link]("Playing music.");

// Usage

class Main {

public static void main(String[] args) {

Car myCar = new Car();

[Link]();

[Link]();

5. How to access Interface Variable?

Variables declared in an interface are implicitly public static final. This


means:

1. They are constants (their value cannot be changed).

2. They are static, meaning they belong to the interface itself, not any
specific implementing object.

3. They are public, meaning they can be accessed from anywhere.

You access an interface variable directly using the Interface Name,


similar to accessing a static variable in a class.

Example:

Java

interface AppConstants {

// Implicitly public static final int MAX_USERS = 100;

int MAX_USERS = 100;

String APP_NAME = "MyJavaApp";

}
class Configuration {

public void showLimit() {

// Accessing variables using Interface Name

[Link]("Application: " + AppConstants.APP_NAME);

[Link]("Maximum Users: " + AppConstants.MAX_USERS);

// AppConstants.MAX_USERS = 200; // ERROR: Cannot assign a value


to a final variable

7. Explain with example how to achieve multiple inheritance with


interface

Java does not support multiple inheritance of classes (a class cannot


extend two classes). However, Java achieves multiple inheritance of
type/contract by allowing a class to implement multiple interfaces.

This is safe because interfaces only declare abstract methods


(contracts), which avoids the ambiguous "Diamond Problem" that occurs
when inheriting state and implementation from two separate parent
classes. The implementing class must provide the concrete
implementation for all methods from all implemented interfaces.

Example:

Java

interface Swimmer {

void swim();

interface Runner {

void run();

// A Person can implement both Swimmer and Runner

class Athlete implements Swimmer, Runner {


@Override

public void swim() {

[Link]("Athlete is swimming fast.");

@Override

public void run() {

[Link]("Athlete is running a marathon.");

class Main {

public static void main(String[] args) {

Athlete a = new Athlete();

[Link](); // Method from Swimmer interface

[Link](); // Method from Runner interface

9. What is a package? How are they created and accessed?


Explain how user-defined packages are created and accessed in
Java.

A package is a mechanism in Java to group related classes,


interfaces, and sub-packages together. They provide a namespace
management system to prevent naming conflicts and control access to
classes through access modifiers (e.g., protected, default).

Creation of a User-Defined Package

1. Declaration: The first statement (non-comment, non-whitespace)


in a Java source file must be the package keyword followed by the
desired package name. Package names are conventionally written in
all lowercase and use dot (.) notation for hierarchical structure
(e.g., [Link]).

Java
// [Link]

package [Link];

public class MyClass {

// Class body

2. Directory Structure: The package name must match the directory


structure on the file system. For [Link], the file
[Link] must be located inside the path com/myapp/data
relative to the source root.

Accessing a User-Defined Package

To use classes from another package, you have three options:

1. Using Fully Qualified Name (FQN):

Java

// In [Link]

[Link] obj = new [Link]();

2. Using the import Statement (Specific Class): This is the most


common approach.

Java

// In [Link]

import [Link];

public class AnotherFile {

MyClass obj = new MyClass(); // No need for FQN

3. Using the import Statement (Wildcard *): Imports all public


classes/interfaces from the specified package (not sub-packages).

Java

// In [Link]

import [Link].*;
public class AnotherFile {

MyClass obj = new MyClass(); // Works

10. What is CLASSPATH? How to Set CLASSPATH in Java.

CLASSPATH is an environment variable or command-line option used by


the Java Virtual Machine (JVM) and Java compiler (javac) to locate user-
defined classes and packages. It is a list of directories, JAR archives, or
ZIP archives that the Java runtime searches when trying to load a class
that is not part of the standard Java libraries.

How to Set CLASSPATH

The classpath can be set in a few ways:

1. Using the Command Line (-cp or -classpath): This is the


recommended way, as it is temporary and only affects the current
execution/compilation.

o To compile:

Bash

javac -cp /path/to/my/libs:/path/to/my/classes [Link]

o To run:

Bash

java -cp /path/to/my/libs:/path/to/my/classes [Link]

o Note: Paths are separated by a colon (:) on Linux/macOS and


a semicolon (;) on Windows.

2. Setting an Environment Variable: Setting a system-wide


CLASSPATH environment variable. This is generally discouraged
because it affects all Java applications and can lead to conflicts.

o Linux/macOS (bash):

Bash

export CLASSPATH=/path/to/my/classes:.:/path/to/[Link]

o Windows (Command Prompt):

Bash

set CLASSPATH=C:\path\to\my\classes;.;C:\path\to\[Link]
3. Using Development Tools (IDE/Build Tools): In modern
development, the classpath is almost always managed
automatically by Integrated Development Environments (IDEs) like
Eclipse or IntelliJ IDEA, or build automation tools like Maven or
Gradle.

12. How to add class and interface to package?

To add a class or interface to a package, you simply need to follow the


package creation and structure rules:

1. Add the Package Declaration: Place the package statement as


the very first non-comment line in the source file (.java).

Java

// Example: [Link]

package [Link]; // This assigns the interface to the


'geometry' package

public interface MyInterface {

void calculate();

Java

// Example: [Link]

package [Link]; // This assigns the class to the 'geometry'


package

public class MyClass {

// ... class content ...

2. Ensure Correct File Location: Save the source file ([Link]


or [Link]) in a directory structure that matches the
package name, relative to a source root directory.

If the source root is /project/src, then:

o [Link] must correspond to the path


/project/src/com/myapp/geometry/.
Once compiled, the resulting .class files will reside in the same directory
structure and are considered part of the declared package.

13. What is an Error? Explain about different types of Errors.

In Java, an Error is a subclass of Throwable that indicates a serious


problem that a reasonable application should not try to catch. Errors are
typically conditions that are external to the application and usually
cannot be recovered from gracefully by the application code. They
occur mostly at runtime.

The main reason for them is often system-level issues, hardware issues, or
resource exhaustion.

Different Types of Errors

Errors belong to the [Link] class and its subclasses. Common


examples include:

1. OutOfMemoryError: Thrown when the Java Virtual Machine (JVM)


cannot allocate an object because it is out of space, and no more
garbage collection can be performed to free up space. (e.g.,
creating too many objects, large arrays).

2. StackOverflowError: Thrown when an application recurses too


deeply, leading to the exhaustion of the execution stack. (e.g.,
infinite recursion without a base case).

3. InternalError: Thrown when a serious internal error or corruption in


the JVM implementation occurs.

4. NoClassDefFoundError: Thrown when the JVM tries to load a class


in the runtime, but that class definition cannot be found (even
though the class was present during compilation).

5. UnknownError: Thrown when an unknown but serious exception


has occurred in the JVM.

14. What is an exception? How it is handled? And also state the


Benefits of exception handling.

What is an Exception?

An Exception is an event that occurs during the execution of a program


that disrupts the normal flow of the program's instructions. In Java, an
Exception is a subclass of [Link] (which is a subclass of
Throwable). Unlike Errors, exceptions are generally recoverable and
should be handled by the application code.

There are two main categories of exceptions:


1. Checked Exceptions: Exceptions that are checked at compile
time. If a method can throw a checked exception (e.g., IOException,
SQLException), it must either handle it using a try-catch block or
declare it using the throws keyword in the method signature.

2. Unchecked Exceptions (Runtime Exceptions): Exceptions that


are not checked at compile time. They are subclasses of
[Link] (e.g., NullPointerException,
ArrayIndexOutOfBoundsException). They usually indicate
programming errors.

How is Exception Handling Done?

Exception handling in Java is primarily done using the try-catch-finally


block:

 try: Encloses the block of code that might throw an exception.

 catch: Follows the try block and specifies the type of exception it
can handle. If an exception occurs in the try block, the control is
passed to the appropriate catch block.

 finally: An optional block that always executes, regardless of


whether an exception was thrown or caught. It is typically used for
cleanup code (e.g., closing file streams, database connections).

Example:

Java

try {

int result = 10 / 0; // This will throw ArithmeticException

[Link]("Result: " + result); // This line is skipped

} catch (ArithmeticException e) {

// Handling the specific exception

[Link]("Error: Cannot divide by zero. Details: " +


[Link]());

} catch (Exception e) {

// Catching any other Exception (should be more specific if possible)

[Link]("An unexpected error occurred.");

} finally {

// This code always executes


[Link]("Execution complete.");

Benefits of Exception Handling

1. Maintaining Normal Flow: It prevents the program from abruptly


terminating when a runtime error occurs, allowing the program to
continue its execution or shut down gracefully.

2. Separation of Concerns: It separates the code that performs the


normal tasks of a program from the code that handles exceptional
circumstances.

3. Robustness: Makes the code more reliable and robust by providing


a clear mechanism to manage and respond to errors.

4. Error Identification: It helps in identifying the type of error that


occurred, often providing detailed information about the cause.

16. Write a brief note on Exception Handling by Using try and


catch Statements.

The try-catch mechanism is the fundamental construct for handling


exceptions in Java. It allows a programmer to specify code that should be
executed if an exception is thrown within a protected block.

 try Block: This is the mandatory first part. The code placed inside
this block is the critical section where an exception might occur. If
an exception occurs, the JVM immediately stops executing the rest
of the code in the try block and looks for a matching catch block.

Java

try {

// Code that might throw an exception (e.g., file I/O, network call, array
access)

 catch Block: This block is executed only if an exception of the


declared type (or a subclass) is thrown in the preceding try block. It
takes a single argument, which is the exception object itself,
providing information about the error. A try block can be followed by
one or more catch blocks to handle different types of exceptions.

Java

catch (ExceptionType identifier) {

// Code to handle the exception, log the error, or attempt recovery


}

// Example with multiple catch blocks:

catch (ArithmeticException e1) { /* handle division by zero */ }

catch (ArrayIndexOutOfBoundsException e2) { /* handle array access


error */ }

Working Principle:

1. The code in the try block executes sequentially.

2. If no exception occurs, the catch blocks are skipped, and execution


resumes after the last catch block (or finally block, if present).

3. If an exception occurs, the JVM creates an Exception object.

4. The JVM searches for the first catch block whose parameter type
matches the type of the thrown Exception object.

5. If a match is found, the code in that catch block executes.

6. If no match is found, the exception is propagated up the call stack.

17. Explain throw statement.

The throw statement in Java is used to explicitly throw an exception


object from any point in the program. This is often used for:

1. Throwing a user-defined (custom) exception.

2. Re-throwing a caught exception after partial processing (see re-


throwing example later).

3. Throwing a built-in exception when an unexpected, unrecoverable


state is reached in business logic.

Syntax

Java

throw new ExceptionClassName("Optional error message");

Example

Suppose a method requires an input to be non-negative.

Java

public void processValue(int value) {

if (value < 0) {

// Explicitly create and throw an exception object


throw new IllegalArgumentException("Value cannot be negative: " +
value);

// Normal processing continues here if value is non-negative

[Link]("Processing value: " + value);

// In the main method:

try {

processValue(-5); // Will cause the exception to be thrown

} catch (IllegalArgumentException e) {

[Link]("Caught exception: " + [Link]());

If the exception thrown is a checked exception, the method throwing it


must declare it using the throws keyword in its signature.

19. Write about finally statement in Java.

The finally block is an optional block associated with a try-catch


structure. The code inside the finally block is guaranteed to execute,
regardless of whether an exception was thrown or caught in the try block.

Purpose

The primary purpose of the finally block is to execute cleanup code, such
as:

 Closing resources (e.g., file streams, database connections, network


sockets).

 Releasing locks.

 Executing any code that must run before the method exits.

Key Execution Rules

1. No Exception: If the try block executes without an exception, the


finally block executes immediately after the try block.

2. Exception Caught: If an exception is thrown and successfully


caught by a catch block, the finally block executes immediately after
the catch block finishes.
3. Uncaught Exception: If an exception is thrown but is not caught
by any catch block, the finally block still executes, and then the
uncaught exception is propagated (re-thrown) up the call stack.

4. return Statement: If the try or catch block contains a return


statement, the finally block executes before the method actually
returns to the caller.

Example

Java

FileReader reader = null;

try {

reader = new FileReader("[Link]");

// Code to read the file...

} catch (IOException e) {

[Link]("File error: " + [Link]());

} finally {

// Cleanup code - guaranteed to run

if (reader != null) {

try {

[Link]();

[Link]("File resource closed.");

} catch (IOException e) {

// Handle exception during close()

21. How to re-throw an exception in Java? Explain with an


example.

Re-throwing an exception means catching an exception, performing


some required action (like logging the error, closing a resource, or
wrapping the exception), and then throwing the same exception or a new
one to be handled by a higher-level caller.

This is useful for:


1. Logging the error at a specific level without fully handling it (i.e., you
don't know how to recover, but you need to log its occurrence).

2. Transforming a low-level exception (like SQLException) into a higher-


level, more meaningful exception (like DataAccessException). This is
called Exception Chaining.

Example (Logging and Re-throwing the Original Exception)

Java

import [Link];

import [Link];

public class FileProcessor {

public void readFile(String filePath) throws IOException {

FileReader reader = null;

try {

reader = new FileReader(filePath);

// ... reading logic ...

[Link]("File read successfully.");

} catch (IOException e) {

// 1. Log the error for debugging

[Link]("LOGGING: Error reading file: " +


[Link]());

// 2. Perform cleanup (which is also done by finally, but shown here


for context)

// 3. Re-throw the exception to notify the caller

throw e;

} finally {

if (reader != null) {

try {

[Link]();
} catch (IOException closeEx) {

// Handle close exception silently or log it

In the example, the readFile method catches the IOException to log it, but
since it cannot fully recover, it re-throws the original exception object
(throw e;) so that its caller must deal with the file I/O failure.

22. Describe the built-in exceptions in Java.

Java provides a rich set of built-in exceptions and errors, all inheriting from
the Throwable class. They are categorized as Errors, Checked
Exceptions, and Unchecked Exceptions (Runtime Exceptions).

1. Unchecked Exceptions (Subclasses of


[Link])

These exceptions are generally caused by programming logic errors


and do not need to be declared in the method signature (though they can
be caught).

Exception Description Example Cause

Attempting
to use an
object Calling a method on
NullPointerException
reference a null object.
that has a
null value.

An
exceptional
Division by zero (int
ArithmeticException arithmetic
result = 10 / 0;).
condition has
occurred.

ArrayIndexOutOfBoundsExc Accessing an myArray[10] when


Exception Description Example Cause

array with an
illegal index
(negative or
eption greater myArray has size 5.
than/equal to
the array
size).

Attempting
to cast an
object to a
String s = (String)
ClassCastException type of
new Object();
which it is
not an
instance.

A method
has been Passing a negative
passed an number to a method
IllegalArgumentException
illegal or that expects a
inappropriat positive one.
e argument.

Attempting
to convert a
string to a
numeric [Link]("ab
NumberFormatException
type, but the c")
string has an
incorrect
format.

2. Checked Exceptions (Subclasses of [Link]


excluding RuntimeException)

These exceptions are typically related to external factors and must be


handled (either by try-catch or by declaring throws) at compile time.
Exception Description Example Cause

Base class for


General failure during
IOException I/O related
input/output operations.
exceptions.

Attempting to
FileNotFoundExcepti new
open a file that
on FileReader("[Link]")
does not exist.

An exception
related to Invalid SQL query,
SQLException
database connection failure.
access.

A thread waiting,
sleeping, or
Calling [Link]()
InterruptedExceptio otherwise
and another thread calls
n engaged in a
interrupt().
long activity is
interrupted.

The application
tries to load a
Attempting to load a
class using its
ClassNotFoundExcep driver class that is
string name but
tion missing from the
no definition for
classpath.
the class is
found.

You might also like