0% found this document useful (0 votes)
4 views43 pages

Java Packages Overview

The document explains Java packages, which are namespaces that group related classes and interfaces, helping to organize large programs, avoid name conflicts, and provide access control. It details the two types of packages: built-in (predefined) and user-defined, along with how to create, access, and import them. Additionally, it highlights the advantages of using packages, such as code organization, reusability, and security.

Uploaded by

manasapatil226
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)
4 views43 pages

Java Packages Overview

The document explains Java packages, which are namespaces that group related classes and interfaces, helping to organize large programs, avoid name conflicts, and provide access control. It details the two types of packages: built-in (predefined) and user-defined, along with how to create, access, and import them. Additionally, it highlights the advantages of using packages, such as code organization, reusability, and security.

Uploaded by

manasapatil226
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

Module4_exception.

pdf
PDF

what is package , explain types of package, how to create


,access and import package with example.

Unique name had to be used for each class to avoid

Package in Java
name collisions.
• Java provides a mechanism for partitioning the class
name space into more manageable Chunks

What is a Package?
package
• The package is both a naming and a visibility control
mechanism

In Java, a package is a namespace that groups related classes, interfaces, and sub-
packages together.

👉 Think of a package as a folder on your computer that stores related files.

Why Packages are Needed


Organizes large programs
Avoids name conflicts (same class name in different packages)
Provides access protection
Makes code reusable and maintainable

Types of Packages in Java

1. Built-in (Predefined) Packages


These are packages provided by Java itself.

Common examples:

[Link] → basic classes ( String , Math , System )

[Link] → utilities ( Scanner , ArrayList )

[Link] → input/output
[Link] → networking

[Link] → database connectivity

📌 [Link] is imported automatically.


2. User-defined Packages
Packages created by the programmer to organize their own classes.

How to Create a Package

Syntax

java

package package_name;
Copy code

Example

java

package mypack;

public class Hello {


public void display() {
[Link]("Hello from package");
}
}

Copy code
📌 Rules
package statement must be the first line

Folder with the same name as package is created automatically

Creating Package using Command Line

bash

javac -d . [Link]
Copy code

This creates:

cpp

mypack/
└── [Link]
Copy code
How to Access a Package Class
There are three ways:

1. Using Fully Qualified Name

java

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


[Link]();
Copy code

✔ No import needed
❌ Long and repetitive

2. Using import statement (Recommended)

java

import [Link];

class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
}

Copy code

3. Import Entire Package

java

import mypack.*;

class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
} Copy code

📌 Imports all classes inside mypack

Access Protection in Packages


Modifier Same Class Same Package Subclass Other Package

public ✔ ✔ ✔ ✔

protected ✔ ✔ ✔ ❌

default ✔ ✔ ❌ ❌

private ✔ ❌ ❌ ❌

Example: User-defined Package (Complete Program)

File: [Link]

java

package college;

public class Student {


public void show() {
[Link]("Student details");
}
}

Copy code

File: [Link]

java

import [Link];

class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}
Copy code

Important Points for Exams


Package = group of related classes
Improves modularity and reusability
package keyword is used to create
import keyword is used to access

Built-in and User-defined are the two types

If you want:
Short exam answer
Diagram of package structure
Viva questions on packages

Just tell me 👍

what is package , explain types of package, how to create


,access and import package with example also give its
advantages and uses . give in detailllllllllllllllllllllll from this
PDF and extra also , give in biggggggggg points,

Below is a VERY DETAILED, EXAM-ORIENTED, BIG-POINTS explanation of JAVA


PACKAGES, written in clear theory style, combining standard textbook/PDF concepts +
extra points.
(Perfect for 10–15 mark answers, viva, and theory exams.)

PACKAGE IN JAVA

1. WHAT IS A PACKAGE?
A package in Java is a namespace that groups related classes, interfaces, sub-packages,
Unique name had to be used for each class to avoid

and other packages together. name collisions.


• Java provides a mechanism for partitioning the class
name space into more manageable Chunks

➡ In simple words: package


• The package is both a naming and a visibility control

👉 A package is a folder (directory) that contains related Java classes and interfaces.
mechanism

Formal Definition

A package is a collection of related classes and interfaces that provides logical


grouping, name conflict resolution, access control, and code reusability.

2. WHY PACKAGES ARE REQUIRED (NEED FOR PACKAGES)


Packages are needed to:
1. Organize large programs
2. Avoid class name conflicts
3. Control access (security)
4. Improve reusability
5. Provide modularity
6. Simplify maintenance
7. Support large-scale software development

3. TYPES OF PACKAGES IN JAVA


Java packages are broadly classified into TWO TYPES:

3.1 BUILT-IN (PREDEFINED) PACKAGES


These are packages provided by Java API (Java Standard Library).

Characteristics
Already available in Java
Contain ready-made classes and interfaces
Reduce development effort
Imported using import keyword

Common Built-in Packages


Package Purpose

[Link] Basic language support

[Link] Utilities (collections, Scanner, Random)

[Link] Input / Output

[Link] Networking

[Link] Database connectivity

[Link] GUI components

[Link] Advanced GUI

📌 Important Note (Exam Point)


👉 [Link] package is automatically imported.

Example of Built-in Package

java

import [Link];

class Test {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int x = [Link]();
[Link](x);
}
}

Copy code

3.2 USER-DEFINED PACKAGES


These are packages created by programmers to organize their own classes.

Characteristics
Created using package keyword
Used for large projects
Improves code structure
Helps in team-based development

4. HOW TO CREATE A PACKAGE

4.1 USING package KEYWORD

Syntax

java

package package_name;
Copy code

📌 Must be the first statement in the source file.

Example

java

package mypack;

public class Hello {


public void show() {
[Link]("Hello from mypack");
}
}

Copy code

4.2 COMPILING USER-DEFINED PACKAGE

bash

javac -d . [Link]
Copy code

Directory Structure Created

cpp
mypack/ Copy code
└── [Link]

5. HOW TO ACCESS A PACKAGE


There are THREE WAYS to access package classes:

5.1 USING FULLY QUALIFIED NAME

Example

java

class Test {
public static void main(String[] args) {
[Link] obj = new [Link]();
[Link]();
}
}

Copy code

Advantages
No import statement required

Disadvantages
Lengthy and repetitive
Reduces readability

5.2 USING import STATEMENT (SINGLE CLASS IMPORT)

Syntax

java

import package_name.ClassName;
Copy code

Example

java
import [Link];

class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
}

Copy code
✔ Most commonly used
✔ Cleaner code

5.3 IMPORTING ENTIRE PACKAGE

Syntax

java

import package_name.*;
Copy code

Example

java

import mypack.*;

class Test {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
}
}

Copy code
📌 * imports all classes of the package (not sub-packages).

6. ACCESS PROTECTION IN PACKAGES


Packages work closely with access specifiers.
Modifier Same Class Same Package Subclass Other Package

public ✔ ✔ ✔ ✔

protected ✔ ✔ ✔ ❌

default ✔ ✔ ❌ ❌

private ✔ ❌ ❌ ❌

📌 Exam Highlight
👉 protected allows access in subclasses outside the package.

7. COMPLETE USER-DEFINED PACKAGE EXAMPLE

File 1: [Link]

java

package college;

public class Student {


public void display() {
[Link]("Student details");
}
}

Copy code

File 2: [Link]

java

import [Link];

class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
Copy code
}

8. ADVANTAGES OF PACKAGES

Major Advantages
1. Code Organization
Logical grouping of related classes
2. Avoids Naming Conflicts
Same class names allowed in different packages
3. Reusability
Packages can be reused across projects
4. Security
Access control using access modifiers
5. Maintenance
Easier debugging and updates
6. Modularity
Large applications divided into modules
7. Team Development
Different teams work on different packages
8. Scalability
Easy to expand large systems

9. USES OF PACKAGES
Packages are used in:
1. Large software applications
2. Enterprise applications
3. Library creation
4. Framework development
5. API design
6. Distributed systems
7. Object-oriented project structuring
10. IMPORTANT EXAM POINTS (VERY IMPORTANT)
package must be first statement

One file can belong to only one package


A package can contain sub-packages
[Link] is imported by default

* does NOT import sub-packages

Packages help in security + reusability

11. ONE-LINE EXAM DEFINITION


A package in Java is a namespace that groups related classes and interfaces together
to achieve modularity, reusability, security, and easy maintenance.

If you want next:


✅ Diagram of package structure
✅ 15-mark answer format
✅ Viva questions + answers
✅ Comparison: package vs interface vs class

Just tell me 🔥

what is interface , characterristics, syntax, with example

Below is a VERY DETAILED, EXAM-READY, BIG-POINTS explanation of INTERFACE IN


JAVA, written in simple but professional theory language, perfect for 10–15 mark
answers, viva, and revision.

INTERFACE IN JAVA

1. WHAT IS AN INTERFACE?
An interface in Java is a blueprint of a class that contains abstract methods, constants,
and (from Java 8 onwards) default and static methods.

👉 In simple words:

An interface specifies WHAT a class must do, but not HOW it does it.

Formal Definition (Exam Ready)

An interface is a completely abstract reference type in Java that is used to achieve


abstraction, multiple inheritance, and standardization of behavior among classes.

2. WHY INTERFACE IS REQUIRED (NEED FOR INTERFACE)


Interfaces are required to:

1. Achieve 100% abstraction


2. Support multiple inheritance
3. Define common behavior for unrelated classes
4. Provide loose coupling
5. Enable plug-and-play architecture
6. Support framework and API design
7. Enforce method implementation rules

3. CHARACTERISTICS OF INTERFACE (VERY IMPORTANT)

Main Characteristics
1. An interface cannot be instantiated
2. Interface methods are:
public and abstract by default

3. Interface variables are:


public static final by default (constants)

4. A class uses implements keyword to use an interface


5. Interface supports multiple inheritance
6. Interface does not contain constructors
7. Interface does not contain instance variables
8. A class must implement all methods of an interface
9. Interfaces can extend other interfaces
10. Interface provides complete abstraction

Exam Highlight
📌 Java allows multiple inheritance through interfaces, but not through classes.

4. SYNTAX OF INTERFACE

Defining an Interface

java

interface InterfaceName {
// constants
// abstract methods
}
Copy code

Implementing an Interface

java

class ClassName implements InterfaceName {


// method implementations
}
Copy code

5. SIMPLE INTERFACE EXAMPLE

Interface Definition

java

interface Animal {
void sound(); // abstract method
Copy code
}

Class Implementing Interface

java

class Dog implements Animal {


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

Copy code

Main Class

java

class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}

Copy code

Output

nginx

Dog barks
Copy code

6. INTERFACE WITH VARIABLES (CONSTANTS)


java

interface Vehicle {
int speed = 80; // public static final by default
void run(); Copy code
}

java

class Bike implements Vehicle {


public void run() {
[Link]("Bike runs at " + speed + " km/h");
}
}

Copy code
📌 Interface variables cannot be modified.

7. MULTIPLE INHERITANCE USING INTERFACE

Interface 1

java

interface A {
void show();
}
Copy code

Interface 2

java

interface B {
void display();
}
Copy code

Class Implementing Multiple Interfaces

java

class Test implements A, B {


public void show() {
[Link]("Show method");
}
public void display() {
[Link]("Display method");
}
}
Copy code

📌 Exam Point
✔ Java allows multiple inheritance using interfaces
❌ Java does NOT allow multiple inheritance using classes

8. INTERFACE EXTENDING ANOTHER INTERFACE


java

interface A {
void methodA();
}

interface B extends A {
void methodB();
}

Copy code

9. DEFAULT AND STATIC METHODS (JAVA 8 FEATURE)

Default Method

java

interface Demo {
default void msg() {
[Link]("Default method");
}
}

Copy code

Static Method
java

interface Demo {
static void show() {
[Link]("Static method");
}
}

Copy code
📌 Default methods provide backward compatibility.

10. DIFFERENCE BETWEEN INTERFACE AND CLASS (EXAM FAVORITE)


Feature Interface Class

Methods Abstract Concrete

Variables Constants Instance variables

Constructors ❌ No ✔ Yes

Multiple Inheritance ✔ Yes ❌ No

Instantiation ❌ No ✔ Yes

11. ADVANTAGES OF INTERFACE


1. Supports multiple inheritance
2. Provides 100% abstraction
3. Ensures method implementation
4. Enables loose coupling
5. Improves scalability
6. Helps in API and framework design
7. Improves testability
8. Promotes standardization

12. USES OF INTERFACE


Interfaces are used in:
1. Large software systems
2. Frameworks
3. API development
4. Enterprise applications
5. Plugin architecture
6. Callback mechanisms
7. Dependency Injection

13. ONE-LINE EXAM DEFINITION


An interface in Java is a reference type that contains abstract methods and constants
and is used to achieve abstraction and multiple inheritance.

14. IMPORTANT EXAM POINTS (VERY VERY IMPORTANT)


Interface methods are public abstract
Variables are public static final
Use implements keyword
Interface cannot be instantiated
Class must implement all methods
Multiple interfaces allowed

If you want next:


✅ Interface vs Abstract Class (full table)
✅ 15-mark answer format
✅ Viva questions & answers
✅ Diagram for interface implementation

Just tell me 🔥

what is exception? how are exception handles in JAVA ?


exaplin with example prog
Below is a VERY DETAILED, EXAM-ORIENTED explanation of EXCEPTION HANDLING IN
JAVA, written in big points, simple language, and with example programs, exactly
suitable for 10–15 mark answers, viva, and theory exams.

EXCEPTION IN JAVA

1. WHAT IS AN EXCEPTION?

Definition
An exception in Java is an abnormal condition or runtime error that disrupts the normal
flow of program execution.

👉 In simple words:

An exception is a problem that occurs during execution of a program.

Formal Definition (Exam-ready)

An exception is an object that represents an error or unexpected event that occurs


during the execution of a Java program.

2. WHY EXCEPTION HANDLING IS REQUIRED


Exception handling is required to:
1. Prevent abnormal program termination
2. Maintain normal program flow
3. Provide meaningful error messages
4. Separate error-handling code from normal code
5. Improve reliability and robustness
6. Handle runtime errors gracefully

3. TYPES OF ERRORS IN JAVA


Java errors are broadly divided into:

1. Compile-time Errors
Syntax errors
Detected by compiler
Example: missing semicolon

2. Run-time Errors (Exceptions)


Occur during execution
Example: divide by zero

3. Logical Errors
Program runs but gives wrong output

4. EXCEPTION HIERARCHY IN JAVA


lua

Throwable
|
|-- Error
|
|-- Exception
|
|-- RuntimeException

Copy code

4.1 Error
Serious problems
Cannot be handled
Example: StackOverflowError, OutOfMemoryError

4.2 Exception
Exceptions that can be handled using exception handling mechanism.

4.3 TYPES OF EXCEPTIONS


1. Checked Exceptions
Checked at compile time
Must be handled
Example: IOException, SQLException

2. Unchecked Exceptions
Occur at runtime
Subclasses of RuntimeException
Example: ArithmeticException, NullPointerException

5. HOW EXCEPTIONS ARE HANDLED IN JAVA


Java handles exceptions using FIVE KEYWORDS:
1. try
2. catch
3. finally
4. throw
5. throws

6. try and catch BLOCK

Syntax

java

try {
// code that may cause exception
}
catch(ExceptionType e) {
// exception handling code
}

Copy code

Example: Divide by Zero

java

class Demo {
public static void main(String args[]) {
try {
int a = 10 / 0;
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Division by zero error");
}
}
}

Copy code
Output

vbnet

Division by zero error


Copy code

7. MULTIPLE catch BLOCKS


Used when multiple exceptions may occur.

java

class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
int b = 42 / a;
int arr[] = {1};
arr[5] = 10;
}
catch (ArithmeticException e) {
[Link]("Divide by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}
}
}

Copy code

8. finally BLOCK
Purpose
Executes always
Used for cleanup operations

Syntax

java

finally {
// cleanup code
}
Copy code

Example

java

class FinallyDemo {
public static void main(String args[]) {
try {
int a = 10 / 2;
[Link](a);
}
finally {
[Link]("Finally block executed");
}
}
}

Copy code

9. throw KEYWORD
Used to explicitly throw an exception.

Syntax

java

throw new ExceptionType("message");


Copy code
Example

java

class ThrowDemo {
static void check(int age) {
if(age < 18)
throw new ArithmeticException("Not eligible");
else
[Link]("Eligible");
}

public static void main(String args[]) {


check(16);
}
}

Copy code

10. throws KEYWORD


Used to declare exceptions that a method may pass to caller.

Example

java

class ThrowsDemo {
static void demo() throws InterruptedException {
[Link](1000);
}

public static void main(String args[]) {


try {
demo();
}
catch (InterruptedException e) {
[Link]("Exception handled");
}
}
}

Copy code
11. USER-DEFINED (CUSTOM) EXCEPTION

Creating Custom Exception

java

class MyException extends Exception {


MyException(String msg) {
super(msg);
}
}

Copy code

Using Custom Exception

java

class Test {
static void check(int x) throws MyException {
if(x > 100)
throw new MyException("Value too large");
}

public static void main(String args[]) {


try {
check(120);
}
catch(MyException e) {
[Link](e);
}
}
}

Copy code

12. ADVANTAGES OF EXCEPTION HANDLING


1. Prevents abnormal termination
2. Maintains program flow
3. Improves reliability
4. Better debugging
5. Separates error handling logic
6. Improves code readability
7. Allows recovery from errors

13. IMPORTANT EXAM POINTS (VERY IMPORTANT)


Exceptions are objects
Parent class is Throwable
try must be followed by catch or finally

Multiple catch blocks allowed


finally always executes

Checked exceptions must be handled


Runtime exceptions need not be declared

14. ONE-LINE EXAM DEFINITION


An exception is a runtime error that disrupts the normal execution of a program, and
exception handling is a mechanism to handle such errors gracefully.

If you want next:


✅ Exception hierarchy diagram
✅ Difference between Error and Exception
✅ Checked vs Unchecked exceptions table
✅ Viva questions & answers

Just tell me 👍

explain try,catch,throw,finally statements with example

Below is a VERY DETAILED, EXAM-ORIENTED explanation of


try , catch , throw , and finally statements in Java, written in BIG POINTS, simple
language, and with clear example programs.
(Perfect for 10–15 mark answers, viva, and theory exams.)

EXCEPTION HANDLING STATEMENTS IN JAVA


Java provides four important statements to handle runtime errors (exceptions):
1. try
2. catch
3. throw
4. finally

1. try STATEMENT

Meaning
The try block is used to enclose the code that may generate an exception.

👉 It allows Java to monitor risky code for errors.

Key Points (Very Important)


Code that may cause an exception is placed inside try
If an exception occurs, remaining statements in try are skipped
A try block must be followed by:
at least one catch OR
a finally block
try cannot exist alone

Syntax

java

try {
// risky code
}
Copy code
Example

java

class TryDemo {
public static void main(String args[]) {
try {
int a = 10 / 0; // exception occurs
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Division by zero error");
}
}
}

Copy code

2. catch STATEMENT

Meaning
The catch block is used to handle the exception thrown by the try block.

👉 It prevents abnormal termination of the program.

Key Points
Each catch handles a specific type of exception
Multiple catch blocks are allowed
The first matching catch is executed
Exception object contains error details

Syntax

java

catch(ExceptionType e) {
// handling code
}
Copy code
Example

java

class CatchDemo {
public static void main(String args[]) {
try {
int x = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Error: " + e);
}
[Link]("Program continues normally");
}
}

Copy code

Output

vbnet

Error: [Link]: / by zero


Program continues normally
Copy code

3. MULTIPLE catch BLOCKS


Used when different exceptions may occur in the same try block.

Example

java

class MultiCatchDemo {
public static void main(String args[]) {
try {
int a = [Link];
int b = 42 / a;
int arr[] = {1};
arr[10] = 5;
}
catch (ArithmeticException e) {
[Link]("Divide by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index error");
}
}
}

Copy code

4. throw STATEMENT

Meaning
The throw statement is used to explicitly generate an exception manually.

👉 Programmer creates and throws an exception object.

Key Points
Used to create custom or predefined exceptions
Control is transferred to nearest catch
Mostly used for validation checks

Syntax

java

throw new ExceptionType("message");


Copy code

Example

java

class ThrowDemo {
static void checkAge(int age) {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
else
[Link]("Eligible to vote");
}

public static void main(String args[]) {


checkAge(16);
}
}

Copy code

Output

pgsql

Exception in thread "main" [Link]: Not eligible to vote


Copy code

5. finally STATEMENT

Meaning
The finally block contains code that always executes, whether an exception occurs or
not.

👉 Used for cleanup operations.

Key Points
Executes after try and catch
Executes even if:
exception occurs
exception does not occur
return statement is present
Commonly used to:
close files
close database connections
release resources

Syntax
java

finally {
// cleanup code
}
Copy code

Example

java

class FinallyDemo {
public static void main(String args[]) {
try {
int a = 10 / 2;
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Error occurred");
}
finally {
[Link]("Finally block executed");
}
}
}

Copy code

Output

powershell

5
Finally block executed
Copy code

6. try–catch–finally COMBINED EXAMPLE


java

class FullDemo {
public static void main(String args[]) {
try {
int a = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Exception caught");
}
finally {
[Link]("Cleanup code executed");
}
}
}

Copy code

7. FLOW OF EXECUTION (EXAM FAVORITE)


1. Program enters try
2. If exception occurs:
catch executes

3. finally executes always


4. Program continues normally

8. IMPORTANT EXAM POINTS (VERY IMPORTANT)


try block must be followed by catch or finally

Multiple catch blocks allowed


throw is used to explicitly raise exception

finally executes always

Exceptions are objects


Exception handling prevents program crash

9. ONE-LINE DEFINITIONS (FOR QUICK REVISION)


try → encloses risky code
catch → handles exception
throw → explicitly generates exception
finally → executes cleanup code always
If you want next:
✅ Difference between throw and throws
✅ Checked vs Unchecked exceptions table
✅ Exception hierarchy diagram
✅ 15-mark exam answer format

Just tell me 👍

types of exception? explain any 5 inbuilt exception with


examples

Below is a VERY DETAILED, EXAM-ORIENTED explanation of


TYPES OF EXCEPTIONS IN JAVA and ANY 5 INBUILT EXCEPTIONS WITH EXAMPLES,
written in BIG POINTS, simple language, and perfect for 10–15 mark answers and viva.

TYPES OF EXCEPTIONS IN JAVA

1. WHAT IS AN EXCEPTION? (Quick Recall)


An exception is a runtime abnormal condition that disrupts the normal flow of execution
of a Java program.

👉 In Java, exceptions are represented as objects.

2. EXCEPTION HIERARCHY (VERY IMPORTANT FOR EXAM)


lua

Throwable
|
|---- Error
|
|---- Exception
|
|---- RuntimeException Copy code

3. TYPES OF EXCEPTIONS IN JAVA


Java exceptions are mainly classified into THREE TYPES:

3.1 ERRORS

Definition
Errors represent serious problems that occur due to system failure and cannot be handled
by the program.

Characteristics
Caused by JVM or hardware
Not recoverable
Not handled using try–catch

Examples
StackOverflowError
OutOfMemoryError
VirtualMachineError

3.2 CHECKED EXCEPTIONS

Definition
Checked exceptions are exceptions that are checked at compile time.

Characteristics
Must be handled using try–catch or throws
Occur due to external factors
Compiler forces handling

Examples
IOException
SQLException
ClassNotFoundException
FileNotFoundException

3.3 UNCHECKED EXCEPTIONS

Definition
Unchecked exceptions occur at runtime and are not checked at compile time.

Characteristics
Subclasses of RuntimeException
Caused due to programming mistakes
Handling is optional but recommended

Examples
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
NumberFormatException

📌 Exam Highlight
Checked → Compile time
Unchecked → Runtime

4. INBUILT (PREDEFINED) EXCEPTIONS


Below are ANY 5 IMPORTANT INBUILT EXCEPTIONS explained in detail with examples.

1. ArithmeticException

Cause
Occurs when an illegal arithmetic operation is performed.

Common Reason
Division by zero
Example

java

class ArithmeticDemo {
public static void main(String args[]) {
int a = 10 / 0;
[Link](a);
}
}

Copy code

Output

pgsql

Exception in thread "main" [Link]: / by zero


Copy code

2. NullPointerException

Cause
Occurs when a null reference is used to access an object or method.

Example

java

class NullDemo {
public static void main(String args[]) {
String s = null;
[Link]([Link]());
}
}

Copy code

Output

[Link]
Copy code
3. ArrayIndexOutOfBoundsException

Cause
Occurs when an array is accessed using an invalid index.

Example

java

class ArrayDemo {
public static void main(String args[]) {
int arr[] = {10, 20, 30};
[Link](arr[5]);
}
}

Copy code

Output

makefile

[Link]: 5
Copy code

4. NumberFormatException

Cause
Occurs when a string is converted into a number, but the string is not numeric.

Example

java

class NumberDemo {
public static void main(String args[]) {
String s = "abc";
int x = [Link](s);
} Copy code
}

Output

lua

[Link]: For input string: "abc"


Copy code

5. ClassNotFoundException

Cause
Occurs when JVM tries to load a class that does not exist.

Type
✔ Checked Exception

Example

java

class ClassDemo {
public static void main(String args[]) {
try {
[Link]("Test");
}
catch (ClassNotFoundException e) { Copy code

[Link]("Class not found");


}
}
}

5. DIFFERENCE BETWEEN CHECKED AND UNCHECKED EXCEPTIONS


(EXAM FAVORITE)
Feature Checked Exception Unchecked Exception

Checked at Compile time Runtime

Compiler forces handling Yes No

Package [Link], [Link] [Link]

Example IOException ArithmeticException

6. IMPORTANT EXAM POINTS (VERY VERY IMPORTANT)


All exceptions are subclasses of Throwable
Errors are not handled
Checked exceptions must be handled
Unchecked exceptions occur due to logic errors
RuntimeException class represents unchecked exceptions
Exception handling avoids abnormal termination

7. ONE-LINE EXAM ANSWERS


ArithmeticException → divide by zero
NullPointerException → accessing null object
ArrayIndexOutOfBoundsException → invalid array index
NumberFormatException → invalid numeric conversion
ClassNotFoundException → missing class at runtime

If you want next:


✅ Difference between Error and Exception
✅ Exception hierarchy diagram
✅ throw vs throws
✅ Viva questions with answers

Just tell me 👍

You might also like