0% found this document useful (0 votes)
3 views35 pages

Nfs Notes PBLJ

The document provides comprehensive notes on Java fundamentals, including its history, features, and key concepts such as object-oriented programming, inheritance, and data types. It compares Java with C++, discusses Java syntax, packages, access modifiers, and the principles of abstraction and polymorphism. Additionally, it includes examples of Java code to illustrate these concepts and their applications in programming.

Uploaded by

Sushmit Singh
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)
3 views35 pages

Nfs Notes PBLJ

The document provides comprehensive notes on Java fundamentals, including its history, features, and key concepts such as object-oriented programming, inheritance, and data types. It compares Java with C++, discusses Java syntax, packages, access modifiers, and the principles of abstraction and polymorphism. Additionally, it includes examples of Java code to illustrate these concepts and their applications in programming.

Uploaded by

Sushmit Singh
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/ 35

NFS – NOTES FOR STUDY

PROJECT BASED LEARNING IN JAVA


WITH LAB
(Notes)
Chapter-1 (Java Fundamentals)
Introduction to Java. Difference between C++ and Java. Keywords,
Tokens, Data types. Use of public, private, and protected.

1|Page
NFS – NOTES FOR STUDY

Introduction to Java
Java is a high-level, robust, object-oriented, and secure programming language. It is both a
programming language and a platform.
• Developed By: Sun Microsystems (acquired by Oracle Corporation) in 1995.
• Father of Java: James Gosling.
• Initial Name: Originally called Oak. The name was changed to Java because "Oak"
was already registered.
Java provides a runtime environment (JRE) and APIs, which makes it a platform-
independent language.

Platform and Portability


• Platform Definition: Any hardware or software environment where a program runs.
• Java as a Platform:
o Java is considered a platform due to its Java Runtime Environment (JRE) and
Application Programming Interface (API).
o Java code is compiled into bytecode which can be executed on multiple
platforms (Write Once, Run Anywhere - WORA).

Features of Java (Java Buzzwords)


Java’s features contribute to its popularity and widespread use. Below are the key
features:

2|Page
NFS – NOTES FOR STUDY

1. Simple
Java is designed to be simple and easy to learn:
• Syntax is clean and similar to C++, making it familiar to existing programmers.
• Complex features like explicit pointers and operator overloading are removed.
• Automatic Garbage Collection eliminates the need to remove unreferenced objects
manually.
2. Object-Oriented
Java follows the Object-Oriented Programming (OOP) paradigm, where everything is
treated as an object. This simplifies software development and maintenance.
Basic OOP Concepts:
• Object: Instance of a class containing data and behavior.
• Class: Blueprint for creating objects.
• Inheritance: Mechanism to reuse existing code.
• Polymorphism: Allows methods to perform different tasks based on the object.
• Abstraction: Hides implementation details.
• Encapsulation: Binds data and methods, restricting direct access to some elements.
3. Platform Independent
• Java is platform-independent due to its ability to compile code into bytecode.
• Bytecode is executed by the Java Virtual Machine (JVM) on any platform,
eliminating platform-specific dependencies.
4. Secured
• Java is known for its robust security features:
o No explicit pointers to prevent unauthorized memory access.
o Programs run inside a sandbox environment.
Key Security Features:
• Classloader: Separates local classes from imported ones for enhanced security.
• Bytecode Verifier: Ensures no illegal code violates object access rights.
• Security Manager: Controls access to resources like file systems or networks.
Additionally, developers can implement security protocols like SSL, JAAS, and
Cryptography.

3|Page
NFS – NOTES FOR STUDY

5. Robust
Java is designed to handle runtime errors and ensure reliability:
• Strong memory management system.
• No use of explicit pointers.
• Automatic Garbage Collection ensures efficient memory cleanup.
• Exception Handling and Type Checking mechanisms provide runtime stability.
6. Architecture Neutral
Java’s design ensures that its applications are independent of underlying hardware
architecture. For example:
• Primitive data types (e.g., int) have consistent sizes across platforms.
• Unlike C, where int size varies (2 bytes on 32-bit and 4 bytes on 64-bit systems),
Java allocates a fixed 4 bytes.
7. Portable
Java’s portability stems from its ability to execute bytecode on any platform with a
compatible JVM. Bytecode does not require any modifications for different platforms.
8. High Performance
• Java’s performance is better than traditional interpreted languages because
bytecode is close to native machine code.
• However, Java is slightly slower than compiled languages like C++ due to its
interpreted nature.
9. Distributed
• Java provides tools like Remote Method Invocation (RMI) and Enterprise JavaBeans
(EJB) to create distributed applications.
• Distributed computing enables files and applications to be accessed remotely.
10. Multithreaded
Java allows concurrent execution of multiple threads within the same program.
• Threads share a common memory area, reducing memory overhead.
• Useful in multimedia, web applications, and real-time systems.
11. Dynamic
Java supports dynamic class loading, meaning classes are loaded into the JVM as required.
• Supports functions from native languages like C and C++.

4|Page
NFS – NOTES FOR STUDY

• Dynamic compilation and garbage collection further enhance its flexibility.

C++ vs Java
Although Java and C++ share similarities, they differ significantly in many aspects:

Feature Java C++

Memory Management Automatic (Garbage Collection) Manual

Pointers Not supported Supported

Platform Dependency Platform Independent Platform Dependent

Default Arguments Not supported Supported

Header Files No (Uses import) Yes

Multiple Inheritance Not supported directly (uses Interfaces) Supported

Java Basic Syntax


Key Components:
1. Object:
o Objects have states and behaviors.
o Example: A dog has states (color, breed) and behaviors (barking, wagging
tail).
2. Class:
o A blueprint that defines the behaviors and states supported by its objects.
3. Methods:
o Represent behaviors. Logic, data manipulation, and actions are executed
within methods.
4. Instance Variables:
o Each object has its own set of instance variables that define its state.
First Java Program:
public class MyFirstJavaProgram {
/* This is my first Java program.

5|Page
NFS – NOTES FOR STUDY

* This will print 'Hello World' as the output.


*/
public static void main(String[] args) {
System.out.println("Hello World"); // prints Hello World
}
}
Important Points:
• Case Sensitivity: Java is case-sensitive. For example, Hello and hello are treated
differently.
• Class Names: Begin with an uppercase letter. For multi-word names, capitalize the
first letter of each word (e.g., MyFirstJavaClass).
• Method Names: Begin with a lowercase letter. Multi-word names should capitalize
the first letter of each subsequent word (e.g., myMethodName).
• Program File Name: Must match the class name exactly (case-sensitive) and have a
.java extension. Example: MyFirstJavaProgram.java.
• Main Method: Every Java program starts execution from the main() method.

Java Packages
A package in Java is a collection of classes, interfaces, and sub-packages that help organize
and group related components. Java has two types of packages:
1. Built-in Packages: Predefined, such as java.util.* or java.io.*.
2. User-Defined Packages: Created by developers to group custom classes and
interfaces.
Advantages of Using Packages
• Reusability: Create reusable components.
• Better Organization: Efficiently manage hundreds of classes.
• Avoid Name Conflicts: Classes with the same name can exist in different packages.
Using Packages
1. Declare the package at the top of the program using package keyword.
2. Import the package using import keyword.

6|Page
NFS – NOTES FOR STUDY

Example:
// Calculator.java
package letmecalculate;

public class Calculator {


public int add(int a, int b) {
return a + b;
}
}
// Demo.java
import letmecalculate.Calculator;

public class Demo {


public static void main(String[] args) {
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}

Sub-Packages
Packages can contain sub-packages to further organize classes. Example:
package letmecalculate.multiply;

public class Multiplication {


public int product(int a, int b) {
return a * b;
}
}
To use this class, import:
import letmecalculate.multiply.Multiplication;

7|Page
NFS – NOTES FOR STUDY

Fully Qualified Names


Avoid imports by using full names:
letmecalculate.Calculator obj = new letmecalculate.Calculator();

Access Modifiers
Java provides four access modifiers to control access levels:

Modifier Within Class Within Package Subclasses Outside Package

Default Yes Yes No No

Private Yes No No No

Protected Yes Yes Yes No

Public Yes Yes Yes Yes

Examples:
1. Default: Accessible only within the package.
2. Private: Accessible only within the class.
3. Protected: Accessible within the package and subclasses.
4. Public: Accessible from anywhere.
Note: Go through the Code for all access modifiers

Java Data Types


Java supports two categories of data types:
1. Primitive Data Types:
o Specify size and type of variable values.
o Include: byte, short, int, long, float, double, char, boolean.
2. Non-Primitive Data Types:
o Also called reference types.
o Include: Strings, Arrays, Classes, Interfaces.
Key Differences:

8|Page
NFS – NOTES FOR STUDY

• Primitive types are predefined, while non-primitive types are created by


programmers.
• Primitive types cannot call methods, whereas non-primitive types can.
• Primitive types always hold values; non-primitive types can be null.
• Primitive types start with lowercase letters; non-primitive types start with
uppercase letters.
Key Terms to Remember
• Bytecode: Intermediate code compiled by the Java compiler, executed by the JVM.
• JVM (Java Virtual Machine): The runtime engine that executes Java bytecode.
• JRE (Java Runtime Environment): Contains the JVM and necessary libraries for
running Java applications.
• SDK (Software Development Kit): Includes tools for Java application development
and the JRE.

Chapter 2 (OOPS using Java)


Use of class and method in Java. Inheritance, Abstraction,
Polymorphism, Encapsulation and data privacy. Difference between
method overloading and method overriding.
#### **Class in Java**
A class is a blueprint or template for creating objects, which have common properties and
behaviors. It is a logical entity and cannot be physical.

##### **Components of a Class**


A class in Java can contain:
- **Fields**: Variables that hold the state of an object.
- **Methods**: Functions that define the behavior of an object.
- **Constructors**: Special methods to initialize objects.
- **Blocks**:
- **Instance Initialization Block (IIB)**: Runs every time an object is created.
- **Static Initialization Block (SIB)**: Runs only once when the class is loaded.

9|Page
NFS – NOTES FOR STUDY

- **Nested Classes and Interfaces**: Classes and interfaces defined within another class.

##### **Syntax of a Class**


```java
class <ClassName> {
// Fields
// Methods
}

### **Static Class in Java**


A static class in Java is not allowed unless it is a nested (inner) class. A static nested class is
a member of the outer class and can be accessed without creating an instance of the outer
class.

##### **Syntax of a Static Nested Class**


```java
class Outer {
static class Nested {
// Methods and fields
}
}
```

##### **Example: Static Nested Class**


```java
public class Outer {
static class Nested {
public void display() {
System.out.println("This is a static nested class");
}

10 | P a g e
NFS – NOTES FOR STUDY

public static void main(String[] args) {


Outer.Nested nested = new Outer.Nested();
nested.display();
}
}
```

**Key Points**:
- Static nested classes can only access static members of the outer class.
- Static nested classes improve modularity and encapsulation.

---

### **Java Inner Classes**


Java allows nesting one class inside another to group related classes and make the code
more maintainable and readable. Inner classes can:
1. Access all members of the outer class, including private ones.
2. Be private or protected, restricting access.

##### **Example: Regular Inner Class**


```java
class OuterClass {
int x = 10;

class InnerClass {
int y = 5;

11 | P a g e
NFS – NOTES FOR STUDY

public int sum() {


return x + y;
}
}

public static void main(String[] args) {


OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.sum());
}
}
```

**Output**: 15

##### **Private Inner Class**


A private inner class is not accessible outside its outer class.
```java
class Outer {
private class Inner {
void display() {
System.out.println("Private Inner Class");
}
}

void showInner() {
Inner inner = new Inner();
inner.display();
}

12 | P a g e
NFS – NOTES FOR STUDY

public class Test {


public static void main(String[] args) {
Outer outer = new Outer();
outer.showInner();
}
}
```

##### **Static Inner Class**


Static inner classes can be accessed without creating an instance of the outer class.
```java
class Outer {
static class Inner {
void display() {
System.out.println("Static Inner Class");
}
}

public static void main(String[] args) {


Outer.Inner inner = new Outer.Inner();
inner.display();
}
}

### **Inheritance in Java**


Inheritance allows one class (child) to acquire properties and behaviors of another class
(parent). It represents the "IS-A" relationship.

13 | P a g e
NFS – NOTES FOR STUDY

##### **Advantages of Inheritance**


- **Code Reusability**: Reuse fields and methods of an existing class.
- **Method Overriding**: Achieve runtime polymorphism.

##### **Syntax of Inheritance**


```java
class Subclass extends Superclass {
// Additional fields and methods
}

##### **Types of Inheritance**


1. **Single Inheritance**: One child inherits from one parent.
2. **Multilevel Inheritance**: A class inherits from another class, which in turn inherits
from another class.
3. **Hierarchical Inheritance**: Multiple classes inherit from one parent.

**Note**: Java does not support multiple inheritance with classes to avoid ambiguity
(diamond problem).

### **Abstraction in Java**


Abstraction hides implementation details and shows only the functionality.

##### **Ways to Achieve Abstraction**


1. **Abstract Classes**: Allow both abstract and non-abstract methods.
2. **Interfaces**: Allow only abstract methods (prior to Java 8). Post-Java 8, interfaces can
have default and static methods.

**Abstract Class Example**:


```java
abstract class Shape {
abstract void draw();

14 | P a g e
NFS – NOTES FOR STUDY

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle");
}
}

public class TestAbstraction {


public static void main(String[] args) {
Shape s = new Circle();
s.draw();
}
}

### **Polymorphism in Java**


Polymorphism means "many forms" and allows performing a single action in multiple
ways.

##### **Types of Polymorphism**


1. **Compile-time Polymorphism** (Method Overloading): Methods with the same name
but different parameters.
2. **Runtime Polymorphism** (Method Overriding): A subclass provides a specific
implementation of a method defined in the parent class.

**Example of Method Overloading**:


```java
class Adder {
static int add(int a, int b) {
return a + b;
}

15 | P a g e
NFS – NOTES FOR STUDY

static double add(double a, double b) {


return a + b;
}
}

public class TestOverloading {


public static void main(String[] args) {
System.out.println(Adder.add(10, 20));
System.out.println(Adder.add(10.5, 20.5));
}
}
```

**Example of Method Overriding**:


```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

16 | P a g e
NFS – NOTES FOR STUDY

public class TestOverriding {


public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime polymorphism.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound with
an object. Static belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?


No, because the main is a static method.

### **Encapsulation in Java**


Encapsulation is the process of wrapping data (fields) and methods together into a single
unit.

##### **Advantages of Encapsulation**


- Controls access to the data.
- Provides security and data hiding.
- Facilitates unit testing.

**Example of Encapsulation**:
```java

17 | P a g e
NFS – NOTES FOR STUDY

class Account {
private String name;
private double balance;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


if (balance > 0) {
this.balance = balance;
}
}
}

public class TestEncapsulation {


public static void main(String[] args) {
Account acc = new Account();
acc.setName("John");
acc.setBalance(5000);
System.out.println("Name: " + acc.getName());

18 | P a g e
NFS – NOTES FOR STUDY

System.out.println("Balance: " + acc.getBalance());


}
}

Chapter-3 (Exception Handing)


Introduction to Exceptions. Difference between error and exception. Use
of try, catch and throw. Difference between throw and throws. Types of
Exceptions, Exception handling in Java.

19 | P a g e
NFS – NOTES FOR STUDY

Java Exception Handling Notes

Exception Object

An exception object is an instance of an exception class created and handed to the Java runtime
when an exceptional event disrupts the normal flow of the application. This is called “to throw an
exception” because Java uses the throw keyword to hand the exception to the runtime. When a
method throws an exception object, the runtime searches the call stack for a corresponding
exception handler.

Exception Hierarchy

All exception classes in Java are subtypes of the java.lang.Exception class, which itself is a subclass of
the Throwable class. The Throwable class has two primary subclasses:

20 | P a g e
NFS – NOTES FOR STUDY

1. Error:

o Represents severe problems that applications cannot typically handle.

o Examples: OutOfMemoryError, StackOverflowError.

2. Exception:

o Represents problems that applications might want to catch and handle.

o Examples: IOException, ArithmeticException.

Exceptions vs Errors

Aspect Exception Error

Definition Problems during program execution. Severe issues like system resource failure.

Handling Can be caught and handled in the program. Not typically handled by the program.

Examples IOException, SQLException. OutOfMemoryError, VirtualMachineError.

Type Checked or unchecked. Always unchecked.

How to Handle an Exception:

Java provides two different options to handle an exception. You can either use the try-catch-finally
approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which
allows an easier cleanup process for resources.

Try-Catch-Finally:

That is the classical approach to handle an exception in Java. It can consist of 3 steps:

· a try block that encloses the code section which might throw an exception,

· one or more catch blocks that handle the exception and

· a finally block which gets executed after the try block was successfully executed or a
thrown exception was handled.

The try block is required, and you can use it with or without a catch or finally block.

1.The Try Block

Let’s talk about the try block first. It encloses the part of your code that might throw the exception.
If your code throws more than one exception, you can choose if you want to:

· use a separate try block for each statement that could throw an exception or

· use one try block for multiple statements that might throw multiple exceptions.

The following example shows a try block which encloses three method calls.

21 | P a g e
NFS – NOTES FOR STUDY

public void performBusinessOperation() {

try {

doSomething("A message");

doSomethingElse();

doEvenMore();

// see following examples for catch and finally blocks

public void doSomething(String input) throws MyBusinessException {

// do something useful ...

throw new MyBusinessException("A message that describes the error.");

public void doSomethingElse() {

// do something else ...

public void doEvenMore() throws NumberFormatException{

// do even more ...

As you can see in the method definitions, only the first and the third method specify an exception.
The first one might throw a MyBusinessException, and the doEvenMore method might throw
a NumberFormatException.

In the next step, you can define one catch block for each exception class you want to handle and
one finally block. All checked exceptions that are not handled by any of the catch blocks need to be
specified.

2.The Catch Block

You can implement the handling for one or more exception types within a catch block. As you can
see in the following code snippet, the catch clause gets the exception as a parameter. You can
reference it within the catch block by the parameter name.

public void performBusinessOperation() {

22 | P a g e
NFS – NOTES FOR STUDY

try {

doSomething("A message");

doSomethingElse();

doEvenMore();

} catch (MyBusinessException e) {

e.printStackTrace();

} catch (NumberFormatException e) {

e.printStackTrace();

The previous code sample shows two catch blocks. One to handle the MyBusinessException and
one to handle the NumberFormatException. Both blocks handle the exceptions in the same way.
Since Java 7, you can do the same with just one catch block.

public void performBusinessOperation() {

try {

doSomething("A message");

doSomethingElse();

doEvenMore();

} catch (MyBusinessException|NumberFormatException e) {

e.printStackTrace();

The implementation of the catch blocks in the previous examples is very basic.
The printStackTrace method which writes the class, message and call stack of the exception to
system out.

com.stackify.example.MyBusinessException: A message that describes the error.

at com.stackify.example.TestExceptionHandling.doSomething(TestExceptionHandling.java:84)

at
com.stackify.example.TestExceptionHandling.performBusinessOperation(TestExceptionHandling.ja
va:25)

In a real application, you might want to use a more advanced implementation. You can, for
example, show an error message to the user and request a different input or you could write a
record into the work log of your batch process. Sometimes, it might even be ok to catch and ignore
the exception.

23 | P a g e
NFS – NOTES FOR STUDY

3.The Finally Block

The finally block gets executed after the successful execution of the try block or after one of
the catch blocks handled an exception. It is, therefore, a good place to implement any cleanup
logic, like closing a connection or an InputStream.

You can see an example of such a cleanup operation in the following code snippet.
The finally block will be executed, even if the instantiation of the FileInputStream throws
a FileNotFoundException or the processing of the file content throws any other exception.

FileInputStream inputStream = null;

try {

File file = new File("./tmp.txt");

inputStream = new FileInputStream(file);

// use the inputStream to read a file

} catch (FileNotFoundException e) {

e.printStackTrace();

} finally {

if (inputStream != null) {

try {

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

As you’ve seen, the finally block provides a good option to prevent any leaks. And before Java 7, it
was a best practice to put all cleanup code into a finally block.

Java throw keyword:

24 | P a g e
NFS – NOTES FOR STUDY

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw keyword
is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

Let's see the example of throw IOException.

throw new IOException("sorry device error);

Println ("normal flow...")

java throw keyword example:

In this example, we have created the validate method that takes an integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

public class TestThrow1{

static void validate(int age){

if(age<18)

throw new ArithmeticException("not valid");

else

System.out.println("welcome to vote");

public static void main(String args[]){

validate(13);

System.out.println("rest of the code...");

throws Keyword (Exception Handling):

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault
that he has not performed check up before the code being used.

25 | P a g e
NFS – NOTES FOR STUDY

Syntax of java throws:

return_type method_name() throws exception_class_name{

//method code

Advantage of Java throws keyword:

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws example:

Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.

import java.io.IOException;

class Testthrows1{

void m()throws IOException{

throw new IOException("device error");//checked exception

void n()throws IOException{

m();

void p(){

try{

n();

}catch(Exception e){System.out.println("exception handled");}

public static void main(String args[]){

Testthrows1 obj=new Testthrows1();

obj.p();

System.out.println("normal flow...");

26 | P a g e
NFS – NOTES FOR STUDY

Exceptions Methods

The Throwable class provides several methods to handle exceptions:

Method Description

getMessage() Returns a detailed message about the exception.

toString() Returns a short description of the exception.

printStackTrace() Prints the stack trace of the exception to the standard error stream.

Types of Exceptions

1. Checked Exceptions:

o Represent conditions that applications should anticipate and recover from.

o Must be declared in a method’s throws clause if not handled directly.

o Examples: IOException, SQLException.

2. Unchecked Exceptions:

o Occur due to programming errors, such as logic or improper API usage.

o Subclassed from RuntimeException.

o Examples: NullPointerException, ArrayIndexOutOfBoundsException.

Examples

Example of Error

public class ErrorExample {

public static void main(String[] args) {

recursiveMethod(10);

public static void recursiveMethod(int i) {

while (i != 0) {

i = i + 1;

recursiveMethod(i);

27 | P a g e
NFS – NOTES FOR STUDY

Output:

Exception in thread "main" java.lang.StackOverflowError

Example of Exception

public class ExceptionExample {

public static void main(String[] args) {

int x = 100;

int y = 0;

int z = x / y; // This line will throw an exception.

Output:

java.lang.ArithmeticException: / by zero

How to Handle Exceptions

1. Try-Catch-Finally

o Enclose the code that might throw an exception in a try block.

o Handle exceptions in one or more catch blocks.

o Use a finally block for cleanup operations that must execute, regardless of an
exception.

Example:

try {

int[] array = new int[3];

System.out.println(array[5]);

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array index is out of bounds.");

} finally {

System.out.println("Cleanup code.");

2. Throwing Exceptions

28 | P a g e
NFS – NOTES FOR STUDY

o Use the throw keyword to explicitly throw an exception.

Example:

public void validateAge(int age) {

if (age < 18) {

throw new IllegalArgumentException("Age must be 18 or older.");

3. Throws Keyword

o Used in a method declaration to specify exceptions that a method might throw.

Example:

public void readFile() throws IOException {

FileReader file = new FileReader("test.txt");

Common Exceptions

1. Checked Exceptions:

o IOException: Issues with input-output operations.

o SQLException: Problems during database interactions.

o ClassNotFoundException: Class not found during runtime.

2. Unchecked Exceptions:

o ArithmeticException: Errors in arithmetic operations, such as division by zero.

o NullPointerException: Accessing a null object reference.

o ArrayIndexOutOfBoundsException: Accessing an invalid index in an array.

Custom Exceptions

Java allows developers to create their own exceptions by extending the Exception or
RuntimeException class.

Example:

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

29 | P a g e
NFS – NOTES FOR STUDY

public class CustomExceptionExample {

public static void main(String[] args) {

try {

validateAge(15);

} catch (InvalidAgeException e) {

System.out.println("Exception caught: " + e.getMessage());

public static void validateAge(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age is less than 18.");

Summary Table of Exception Handling

Component Description

try block Code that might throw an exception.

catch block Code to handle the exception.

finally block Code that executes after try and catch, used for cleanup.

throw Used to explicitly throw an exception.

throws Declares exceptions a method might throw.

Detailed Notes on Runtime and Checked Exceptions in Java

Runtime - Unchecked Exceptions

Unchecked exceptions in Java are subclasses of RuntimeException. They occur due to programming
errors, such as invalid arguments or logical issues. They are not checked at compile time, so the
programmer is not required to handle them explicitly.

30 | P a g e
NFS – NOTES FOR STUDY

Common Runtime Exceptions

1. ArithmeticException:

o Occurs due to arithmetic errors, such as division by zero.

o Example:

o int result = 10 / 0; // Throws ArithmeticException

2. ArrayIndexOutOfBoundsException:

o Thrown when an array is accessed with an invalid index.

o Example:

o int[] array = new int[5];

o array[10] = 3; // Throws ArrayIndexOutOfBoundsException

3. ArrayStoreException:

o Happens when trying to store an incompatible type in an array.

o Example:

o Object[] array = new String[5];

o array[0] = 10; // Throws ArrayStoreException

4. ClassCastException:

o Occurs when an object is cast to a class that it is not an instance of.

o Example:

o Object obj = new Integer(10);

o String str = (String) obj; // Throws ClassCastException

5. NullPointerException:

o Thrown when attempting to use a null object reference.

o Example:

o String str = null;

o System.out.println(str.length()); // Throws NullPointerException

6. NumberFormatException:

o Occurs when trying to convert an invalid string into a numeric format.

o Example:

o int number = Integer.parseInt("invalid"); // Throws NumberFormatException

7. IllegalArgumentException:

o Thrown when a method is invoked with inappropriate arguments.

31 | P a g e
NFS – NOTES FOR STUDY

o Example:

o Thread.sleep(-1); // Throws IllegalArgumentException

8. IllegalStateException:

o Indicates that a method has been invoked at an inappropriate time.

o Example:

o Iterator<String> it = new ArrayList<String>().iterator();

o it.next(); // Throws IllegalStateException

9. StringIndexOutOfBoundsException:

o Thrown when attempting to access an invalid index of a string.

o Example:

o String str = "example";

o char ch = str.charAt(10); // Throws StringIndexOutOfBoundsException

10. UnsupportedOperationException:

o Occurs when an unsupported operation is attempted.

o Example:

o List<String> list = Collections.unmodifiableList(new ArrayList<>());

o list.add("test"); // Throws UnsupportedOperationException

Checked Exceptions

Checked exceptions are exceptions that must be either caught or declared in the method signature
using the throws keyword. They are checked at compile time.

Common Checked Exceptions

1. SQLException:

o Occurs when there is an error interacting with a database.

o Example:

o Connection conn = DriverManager.getConnection("invalid-url");

2. IOException:

o Occurs during input-output operations, such as reading or writing files.

o Example:

o BufferedReader br = new BufferedReader(new FileReader("nonexistent.txt"));

3. ClassNotFoundException:

32 | P a g e
NFS – NOTES FOR STUDY

o Thrown when the JVM cannot find the required class.

o Example:

o Class.forName("com.unknown.Class");

4. InstantiationException:

o Occurs when trying to instantiate an abstract class or interface.

o Example:

o Class<?> clazz = AbstractClass.class;

o clazz.newInstance();

5. NoSuchMethodException:

o Thrown when an attempt is made to access a method that does not exist.

o Example:

o Method method = String.class.getMethod("unknownMethod");

6. InterruptedException:

o Occurs when a thread is interrupted during its execution.

o Example:

o Thread.sleep(1000); // Throws InterruptedException

Java Custom Exception

Custom exceptions allow developers to define application-specific errors.

Creating a Custom Exception

1. Define a class that extends Exception or RuntimeException.

2. Add a constructor to pass custom error messages.

Example:

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

public class CustomExceptionDemo {

static void validateAge(int age) throws InvalidAgeException {

33 | P a g e
NFS – NOTES FOR STUDY

if (age < 18) {

throw new InvalidAgeException("Age must be 18 or above.");

public static void main(String[] args) {

try {

validateAge(16);

} catch (InvalidAgeException e) {

System.out.println("Exception caught: " + e.getMessage());

Output:

Exception caught: Age must be 18 or above.

Key Points to Remember

1. Runtime Exceptions:

o Do not require explicit handling.

o Examples include NullPointerException, ArithmeticException, and


IndexOutOfBoundsException.

2. Checked Exceptions:

o Must be handled explicitly using try-catch or declared in the method signature.

o Examples include IOException, SQLException, and ClassNotFoundException.

3. Custom Exceptions:

o Use them for application-specific errors.

o Extend the Exception class for checked exceptions and RuntimeException for
unchecked exceptions.

4. Best Practices:

o Catch specific exceptions rather than generic ones.

o Avoid empty catch blocks.

o Use custom exceptions for meaningful error messages.

34 | P a g e
NFS – NOTES FOR STUDY

o Clean up resources in a finally block or use try-with-resources for automatic


management.

These notes provide a comprehensive understanding of Java's exception handling mechanism,


including runtime exceptions, checked exceptions, and custom exception creation.

35 | P a g e

You might also like