0% found this document useful (0 votes)
31 views121 pages

JAVA Notes

Complete java notes.Useful for students of java
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)
31 views121 pages

JAVA Notes

Complete java notes.Useful for students of java
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

Chapter 1 : Introduction to java , Classes and

Object

Static block ,static methods and static fields


Defination :

A static block in Java is used to initialize static variables. It gets executed once when the
class is loaded into memory, before the main() method or any object of the class is created.

🔹 Key Points:
●​ A class can have multiple static blocks.​

●​ Static blocks are executed in the order they appear in the class.​

●​ Used commonly for initializing static data, especially when the initialization is complex
and can't be done in a single line.​

public class StaticBlockExample


{

static int number;

static {
System.out.println("Static block executed.");
number = 100;
}

public static void main(String[] args) {


System.out.println("Main method executed.");
System.out.println("Value of number: " + number);
}
}
✅ Static Field and Static Method in Java
In Java, the static keyword is used to indicate that a field or method belongs to the class
rather than instances (objects) of the class.

🔹 1. Static Field (Variable)


●​ A static field is shared by all objects of the class.​

●​ It is initialized only once when the class is loaded.​

●​ It is accessed using the class name, or through an object (not recommended).​

🔹 2. Static Method
●​ A static method belongs to the class, not to any object.​

●​ It can access only static data (not instance variables unless an object is used).​

●​ It can be called using the class name (recommended).

public class Employee {

// static fields
static String companyName = "TCS";

// Instance fields
int empId;
String empName;

Employee(int id, String name)


{
empId = id;
empName = name;
}
// Instance method
void display() {
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Company: " + companyName);
}

// Static method
static void changeCompany(String newCompany) {
companyName = newCompany;
System.out.println("Company name changed to: " + companyName);
}

public static void main(String[] args)


{
// Accessing static method
Employee.changeCompany("Infosys");

// Creating objects
Employee e1 = new Employee(101, "Neha");
Employee e2 = new Employee(102, "Amit");

e1.display();
System.out.println("-----");
e2.display();
}
}

—--------------------------------------------------------------------------------------------------------------------------

class Account
{
int accountNo;
double balance;
static double rate = 0.05; // Static field shared by all accounts

void setData(int n, double bal) {


accountNo = n;
balance = bal;
}

// Method to calculate quarterly interest


void quarterRateCal() {
double interest = balance * rate * 0.25;
balance += interest;
}

// Static method to modify interest rate


static void modifyRate(double incr) {
rate += incr;
System.out.println("Modified rate of Interest: " + rate);
}

// Method to display account information


void show() {
System.out.println("Account Number: " + accountNo);
System.out.println("Rate of Interest: " + rate);
System.out.println("Balance: ₹" + balance);
}

public static void main(String[] args) {


Account acc1 = new Account();
Account acc2 = new Account();

// Modify the static interest rate


Account.modifyRate(0.01); // Now rate becomes 0.06

System.out.println("\nCustomer 1 Information:");
acc1.setData(201, 1000);
acc1.quarterRateCal();
acc1.show();

System.out.println("\nCustomer 2 Information:");
acc2.setData(202, 1500);
acc2.quarterRateCal();
acc2.show();
}
}

—----------------------------------------------------------------------------------------------------------------------------
✅ What are Predefined Classes in Java?
Predefined classes in Java are built-in classes provided by the Java Standard Library
(JDK) to help developers perform common tasks without having to write code from scratch.

These classes are already defined by Java and organized into packages such as java.lang,
java.util, java.io, etc.

Package Class Name Purpose

java.lang String For text and string operations

math For mathematical functions

Object Parent class of all classes

Integer, Double For wrapper classes


(primitive to object)

java.util Scanner For input from keyboard

ArrayList Resizable array

Date, Calendar Date and time manipulation

java.io File, BufferedReade File handling

java.awt / javax.swing Button, JFrame GUI development

✅ Object Class in Java


The Object class in Java is the superclass of all classes. Every class in Java implicitly
extends the Object class unless it extends another class explicitly.
🧾 Key Methods of the Object Class
toString() Returns a string representation of the object

equals(Object obj) Compares two objects for equality

hashCode() Returns an integer hash code for the object

getClass() Returns the runtime class of the object

clone() Creates a copy of the object (shallow copy)

finalize() Called by garbage collector before


destruction

wait(), notify(), notifyAll() Used for thread synchronization

—----------------------------------------------------------------------------------------------------------------------------

class Rectangle extends Object


{
private double length,breadth;
Rectangle(double x , double y)
{
length = x ;
breadth = y;
}

public void area()


{
System.out.println("Area of Rectangle is = "+(length * breadth));
}

public void circumferrance()


{
System.out.println("Circumferrance of Rectangle is ="+2*(length + breadth));
}
public static void main(String args[])
{
Rectangle r = new Rectangle(10,20);
Rectangle r1 = new Rectangle(10,20);
System.out.println("String Representation = "+ r.toString());
System.out.println("Class Name = "+r.getClass());
System.out.println("Hash Code = "+r.hashCode());
System.out.println("r.equals(r1) = "+ r.equals(r1));

}
}

—----------------------------------------------------------------------------------------------------------------------------

import java.util.Random;

class Bank {
static String bankName;

static {
bankName = "Secure Bank India";
System.out.println("Bank Initialized: " + bankName);
}

String customerName;
int accountNo;

Bank(String name, int accNo) {


customerName = name;
accountNo = accNo;
}

public static int generateOTP() {


Random rand = new Random();
int otp = 100000 + rand.nextInt(900000); // 6-digit OTP
return otp;
}

public void requestOTP() {


System.out.println("\nCustomer: " + customerName);
System.out.println("Account Number: " + accountNo);
int otp = generateOTP();
System.out.println("Generated OTP: " + otp);
}

public static void main(String[] args) {


Bank c1 = new Bank("Ravi Kumar", 12345678);
c1.requestOTP();

Bank c2 = new Bank("Priya Sharma", 87654321);


c2.requestOTP();
}
}

—----------------------------------------------------------------------------------------------------------------------------

Inheritance
Single Inheritance

class Parent {
// parent class
}

class Child extends Parent {


// child class
}

Example :

class Account
{
​ int accountNo;
​ double balance;
​ void setData(int accNo, double bal) {
​ accountNo = accNo;
​ balance = bal;
​ }

​ void displayBalance() {
​ System.out.println("Account Number: " + accountNo);
​ System.out.println("Balance: ₹" + balance);
​ }
}

class SavingAccount extends Account {


​ double interestRate = 0.05;

​ void calculateInterest() {
​ double interest = balance * interestRate;
​ System.out.println("Interest (5%): ₹" + interest);
​ }
}

class Test
{
​ public static void main(String[] args)
{
​ SavingAccount sa = new SavingAccount();
​ sa.setData(123456, 10000);
​ sa.displayBalance();
​ sa.calculateInterest();
}
}
—-------------------------------------------------------------------

MultiLevel

// Base class
class Person {
String name;

void getName(String n) {
name = n;
}

void showName() {
System.out.println("Name: " + name);
}
}

// Derived class from Person


class Employee extends Person {
int empId;

void getEmpId(int id) {


empId = id;
}

void showEmpId() {
System.out.println("Employee ID: " + empId);
}
}

// Derived class from Employee


class Manager extends Employee {
String department;
void getDepartment(String dept) {
department = dept;
}

void showDetails() {
showName(); // from Person
showEmpId(); // from Employee
System.out.println("Department: " + department);
}

public static void main(String[] args) {


Manager m = new Manager();
m.getName("Anita Sharma");
m.getEmpId(2025);
m.getDepartment("Finance");

m.showDetails();
}
}

—------------------------------------------------------------------------------

Hierarchical inheritance

// Parent class
class Account {
int accountNo;
double balance;

void setAccount(int accNo, double bal) {


accountNo = accNo;
balance = bal;
}

void showAccount() {
System.out.println("Account Number: " + accountNo);
System.out.println("Balance: ₹" + balance);
}
}

// Child class 1
class SavingsAccount extends Account {
void calculateInterest() {
double interest = balance * 0.05;
System.out.println("Savings Interest (5%): ₹" + interest);
}
}

// Child class 2
class CurrentAccount extends Account {
void checkMinimumBalance() {
if (balance < 1000) {
System.out.println("Warning: Balance below minimum
requirement!");
} else {
System.out.println("Balance is sufficient.");
}
}
}

// Main class to test both


public class Main {
public static void main(String[] args) {
// Object of SavingsAccount
SavingsAccount sa = new SavingsAccount();
sa.setAccount(1111, 5000);
System.out.println("Savings Account Info:");
sa.showAccount();
sa.calculateInterest();

System.out.println();

// Object of CurrentAccount
CurrentAccount ca = new CurrentAccount();
ca.setAccount(2222, 800);
System.out.println("Current Account Info:");
ca.showAccount();
ca.checkMinimumBalance();
}
}

—------------------------------------------------------------------------------------

Use of ‘Super’ keyword

✅ Use of super Keyword in Java


The super keyword in Java is used to refer to the immediate parent class object.
It helps in accessing:

1.​ Parent class constructor​


2.​ Parent class methods​

3.​ Parent class data members (variables)

📌 Key Points:
●​ super is used only in child class.​

●​ The call to super() must be the first statement in the constructor.​

●​ You can use super to override and extend the behavior of parent class.

Example :

🔹 1. Using super to access parent class variable


If the child class has a variable with the same name as the parent class,
super.variable is used to refer to the parent class variable.

class Animal {

​ String color = "White";

class Dog extends Animal {

​ String color = "Black";

​ void printColor() {

​ System.out.println("Dog color: " + color); ​ // Child class color


​ System.out.println("Animal color: " + super.color); // Parent class
color

​ }

public class Main{

​ public static void main(String[] args) {

​ Dog d = new Dog();

​ d.printColor();

​ }

🔹 2. Using super to call parent class method


class Animal {

​ void sound() {

​ System.out.println("Animal makes a sound");

​ }

class Dog extends Animal {

​ void sound() {

​ System.out.println("Dog barks");

​ }

​ void displaySound() {
​ sound(); ​ // Calls child class method

​ super.sound(); // Calls parent class method

​ }

public class Main{

​ public static void main(String[] args) {

​ Dog d = new Dog();

​ d.displaySound();

​ }

🔹 3. Using super() to call parent class constructor


class Animal {

​ Animal() {

​ System.out.println("Animal constructor called");

​ }

class Dog extends Animal {

​ Dog() {

​ super(); // Call parent class constructor

​ System.out.println("Dog constructor called");

​ }

}
public class Main{

​ public static void main(String[] args) {

​ Dog d = new Dog();

​ }

Method Overriding and Runtime Polymorphism

✅ Method Overriding in Java


Method Overriding occurs when a subclass provides a specific implementation of
a method that is already defined in its superclass. It allows runtime polymorphism.

🔹 Key Points:
●​ Method name, return type, and parameters must be the same.​

●​ It occurs between parent and child classes.​

●​ The overridden method in the child class replaces the parent class version at
runtime.

class Bank {
​ double getInterestRate() {
​ return 5.0; // base interest rate
​ }
}

class SBI extends Bank {


​ double getInterestRate() {
​ return 6.5;
​ }
}

class HDFC extends Bank {



​ double getInterestRate() {
​ return 7.0;
​ }
}

public class BankExample {


​ public static void main(String[] args) {
​ Bank b1 = new SBI(); // Upcasting
​ Bank b2 = new HDFC(); // Upcasting

​ System.out.println("SBI Interest Rate: " + b1.getInterestRate() + "%");


​ System.out.println("HDFC Interest Rate: " + b2.getInterestRate() + "%");
​ }
}

—---------------------------------------------------------------------------------------------------------

Runtime Polymorphism

✅ What is Runtime Polymorphism in Java?


Runtime Polymorphism (also called Dynamic Method Dispatch) in Java is a form
of method overriding where the call to an overridden method is resolved at
runtime and not at compile time.
It is one of the core concepts of Object-Oriented Programming and provides
flexibility and reusability by allowing the same method name to behave differently
based on the object type.

Example :

// Parent class
class Bank {
double getRateOfInterest() {
return 0.0;
}
}

// Child class 1
class SBI extends Bank {
double getRateOfInterest() {
return 5.5;
}
}

// Child class 2
class HDFC extends Bank {
double getRateOfInterest() {
return 6.75;
}
}

// Child class 3
class ICICI extends Bank {
double getRateOfInterest() {
return 6.25;
}
}

// Main class
public class TestPolymorphism {
public static void main(String[] args) {
Bank b; // superclass reference
b = new SBI(); // upcasting
System.out.println("SBI Interest Rate: " + b.getRateOfInterest() + "%");

b = new HDFC(); // upcasting


System.out.println("HDFC Interest Rate: " + b.getRateOfInterest() + "%");

b = new ICICI(); // upcasting


System.out.println("ICICI Interest Rate: " + b.getRateOfInterest() + "%");
}
}

🔁 What is Upcasting in Java?


These are type conversion techniques used with inheritance and
polymorphism in Java, allowing objects to be treated as instances of their
superclass or subclass.

Usage of ‘final’ keyword

Final Variable in Java :

In Java, the final keyword is used to declare constants. When a variable is


marked as final, its value cannot be changed once initialized.

🔑 Key Points about final Variable:


●​ A final variable must be initialized only once.​

●​ Once assigned, the value cannot be modified.​

Example :

public class FinalExample {


public static void main(String[] args) {

final int number = 10; // final variable

// number = 20;

System.out.println("The value is: " + number);

Example 2 :

public class FinalExample {

public static void main(String[] args)

int x = 10 ;

final int y = 20;

System.out.println("x is "+x);

System.out.println("x is "+y);

x = 30;

y = 40;

System.out.println("x is "+x);

System.out.println("x is "+y);

🔐 final Methods in Java – Explanation with Example


In Java, when a method is declared as final, it cannot be overridden by
subclasses.

It is used To prevent modification of important logic in subclasses.

Example :

class Bank {

final void displayInterestRate()

System.out.println("Interest Rate is 5%");

class SBI extends Bank {

// ❌ This will cause an error if uncommented


/*

void displayInterestRate() {

System.out.println("SBI Interest Rate is 6%");

*/

public class Main {

public static void main(String[] args) {

SBI sbi = new SBI();


sbi.displayInterestRate(); // Calls the final method from Bank class

🧱 final Class in Java – Explanation with Suitable Example


In Java, when a class is declared as final, it cannot be inherited (i.e., no
other class can extend it).

✅ Why Use a final Class?


●​ To prevent inheritance for security or design reasons.​

●​ To protect code logic from being altered in subclasses.

Example

final class Bank

void showBankDetails() {

System.out.println("Bank: RBI");

// ❌ This will cause a compile-time error


/*

class SBI extends Bank {


void showBankDetails() {

System.out.println("Bank: SBI");

*/

public class Main {

public static void main(String[] args) {

Bank b = new Bank();

b.showBankDetails();

---------------------------------------------------------------------------------------------------------

Abstract Classes and Abstract methods in java


Example :
import java.util.Scanner;

abstract class Shape {

abstract void area(); // abstract method

void display()

System.out.println("\n Non_Abstract method of class Shape");


}

class Rectangle extends Shape {

double length, breadth;

Rectangle(double l, double b) {

length = l;

breadth = b;

// Implementation of abstract method

void area() {

double a = length * breadth;

System.out.println("Area of Rectangle: " + a);

class Circle extends Shape {

double radius;

Circle(double r) {

radius = r;

void area() {

double a = Math.PI * radius * radius;


System.out.println("Area of Circle: " + a);

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter length of rectangle: ");

double l = sc.nextDouble();

System.out.print("Enter breadth of rectangle: ");

double b = sc.nextDouble();

Shape rect = new Rectangle(l, b); // Upcasting

rect.area();

rect.display();

System.out.println();

System.out.print("Enter radius of circle: ");

double r = sc.nextDouble();

Shape circ = new Circle(r); // Upcasting

circ.area();

sc.close();

}
}

Example 2 :

// Abstract class

abstract class Student {

int id;

String name;

String phone;

String email;

// Constructor

Student(int id, String name, String phone, String email) {

this.id = id;

this.name = name;

this.phone = phone;

this.email = email;

// 3 abstract methods

abstract void displayDetails();

abstract String getCourse();

abstract void calculateFees();


}

// Subclass 1 – Undergraduate Student

class UGStudent extends Student {

UGStudent(int id, String name, String phone, String email) {

super(id, name, phone, email);

void displayDetails() {

System.out.println("UG Student Details:");

System.out.println("ID: " + id + ", Name: " + name);

System.out.println("Phone: " + phone + ", Email: " + email);

String getCourse() {

return "B.Sc Computer Science";

void calculateFees() {

System.out.println("UG Course Fee: ₹55,000 per year");

}
// Subclass 2 – Postgraduate Student

class PGStudent extends Student {

PGStudent(int id, String name, String phone, String email) {

super(id, name, phone, email);

void displayDetails() {

System.out.println("PG Student Details:");

System.out.println("ID: " + id + ", Name: " + name);

System.out.println("Phone: " + phone + ", Email: " + email);

String getCourse() {

return "M.Sc Data Science";

void calculateFees() {

System.out.println("PG Course Fee: ₹60,000 per year");

// Main class

public class Main {


public static void main(String[] args) {

// UG Student

Student ug = new UGStudent(101, "Aarti Sharma", "9876543210",


"[email protected]");

ug.displayDetails();

System.out.println("Course: " + ug.getCourse());

ug.calculateFees();

System.out.println();

// PG Student

Student pg = new PGStudent(202, "Ravi Kumar", "9123456789",


"[email protected]");

pg.displayDetails();

System.out.println("Course: " + pg.getCourse());

pg.calculateFees();

—------------------------------------------------------------------------------------------------------------------

Interface
✅ Syntax:
interface InterfaceName {
void method1();

void method2();

Example
// BankAccountExample.java

interface BankAccount {

void deposit(double amount);

void withdraw(double amount);

void displayBalance();

class SavingsAccount implements BankAccount {

private double balance = 0;

public void deposit(double amount) {

balance += amount;

System.out.println("Savings: Deposited Rs" + amount);

public void withdraw(double amount) {

if (balance >= amount) {

balance -= amount;
System.out.println("Savings: Withdrawn Rs" + amount);

} else {

System.out.println("Savings: Insufficient balance");

public void displayBalance() {

System.out.println("Savings Balance: Rs" + balance);

class CurrentAccount implements BankAccount {

private double balance = 0;

public void deposit(double amount) {

balance += amount;

System.out.println("Current: Deposited Rs" + amount);

public void withdraw(double amount) {

if (balance - amount >= -5000) { // overdraft limit

balance -= amount;
System.out.println("Current: Withdrawn Rs" + amount);

} else {

System.out.println("Current: Overdraft limit exceeded");

public void displayBalance() {

System.out.println("Current Balance: Rs" + balance);

public class Main {

public static void main(String[] args) {

// Using interface reference

BankAccount sa = new SavingsAccount();

sa.deposit(1000);

sa.withdraw(300);

sa.displayBalance();

System.out.println();
BankAccount ca = new CurrentAccount();

ca.deposit(2000);

ca.withdraw(6500); // should allow within overdraft

ca.displayBalance();

Example 2 :

// EmployeeManagementExample.java

interface Employee {

void displayDetails();

double calculateSalary();

class FullTimeEmployee implements Employee {

private int id;

private String name;

private double basicSalary;

private double hra;


public FullTimeEmployee(int id, String name, double basicSalary, double hra) {

this.id = id;

this.name = name;

this.basicSalary = basicSalary;

this.hra = hra;

public void displayDetails() {

System.out.println("Full-Time Employee Details:");

System.out.println("ID: " + id + ", Name: " + name);

public double calculateSalary() {

double salary = basicSalary + hra;

System.out.println("Total Salary: ₹" + salary);

return salary;

class PartTimeEmployee implements Employee {

private int id;

private String name;

private int hoursWorked;


private double hourlyRate;

public PartTimeEmployee(int id, String name, int hoursWorked, double


hourlyRate) {

this.id = id;

this.name = name;

this.hoursWorked = hoursWorked;

this.hourlyRate = hourlyRate;

public void displayDetails() {

System.out.println("Part-Time Employee Details:");

System.out.println("ID: " + id + ", Name: " + name);

public double calculateSalary() {

double salary = hoursWorked * hourlyRate;

System.out.println("Total Salary: ₹" + salary);

return salary;

public class Main {


public static void main(String[] args) {

// Full-time employee

Employee e1 = new FullTimeEmployee(101, "Anita Verma", 25000, 5000);

e1.displayDetails();

e1.calculateSalary();

System.out.println();

// Part-time employee

Employee e2 = new PartTimeEmployee(202, "Rohan Mehta", 40, 300);

e2.displayDetails();

e2.calculateSalary();

—--------------------------------------------------------------------------------------------------------

Runtime Polymorphism using Interface


Extending interface ;

🔷 What is Extending an Interface in Java?


In Java, interfaces can extend other interfaces using the extends keyword.
This allows one interface to inherit the abstract method declarations from another
interface, just like classes can inherit from other classes.

🔹 Key Points:
●​ An interface cannot implement another interface, it can only extend it.​

●​ An interface can extend multiple interfaces (this is Java’s way of


achieving multiple inheritance for interfaces).​

●​ The child interface inherits all the abstract methods from the parent
interface(s).

🔶 Syntax:
interface ParentInterface {
void method1();
}

interface ChildInterface extends ParentInterface {


void method2();
}

Example 1 :

/// Base interface


interface Person {
void displayPersonDetails();
}

// Extended interface
interface Employee extends Person {
void displayEmployeeDetails();
}

// Class implementing the extended interface


class Manager implements Employee {
String name;
int age;
String employeeId;
String department;

// Constructor to initialize employee data


Manager(String name, int age, String employeeId, String department) {
this.name = name;
this.age = age;
this.employeeId = employeeId;
this.department = department;
}

public void displayPersonDetails() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public void displayEmployeeDetails() {


System.out.println("Employee ID: " + employeeId);
System.out.println("Department: " + department);
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating Manager object using constructor
Manager mgr = new Manager("Rajesh Kumar", 35, "EMP1023", "HR");

// Displaying details
mgr.displayPersonDetails(); // From Person interface
mgr.displayEmployeeDetails(); // From Employee interface
}
}

Partial Interface
Example :

interface Bank {
void openAccount();
void deposit(double amount);
void withdraw(double amount);
void checkBalance();
}

// Abstract class with partial implementation of Bank interface


abstract class PartialBank implements Bank {
protected double balance = 0;
public void openAccount() {
System.out.println("Bank account opened.");
balance = 0;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

// withdraw() and checkBalance() are not implemented here


}

// Concrete class that completes the implementation


class MyBank extends PartialBank {
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance.");
}
}

public void checkBalance() {


System.out.println("Current Balance: " + balance);
}
}

// Main class to test the bank operations


public class BankApp {
public static void main(String[] args) {
MyBank bank = new MyBank();
bank.openAccount();
bank.deposit(1000);
bank.withdraw(400);
bank.checkBalance();
}
}

Extending Multiple Interfaces:

✅ What is Multiple Inheritance?


Multiple inheritance means a class can inherit features (fields and methods) from
more than one parent class.

class A {

void show() {

System.out.println("A");

class B {

void show() {

System.out.println("B");

// ❌ Invalid in Java
class C extends A, B {

// Which show() should be called? A or B?

Example 2

interface A {

void show();
}

interface B {

void display();

class C implements A, B {

public void show() {

System.out.println("From A");

public void display() {

System.out.println("From B");

public class Main {

public static void main(String[] args) {

C obj = new C();

obj.show();

obj.display();

Example 3

// Salary interface
interface Salary {

void calculateSalary();

// Tax interface

interface Tax {

void calculateTax();

// Employee class implementing both interfaces (Multiple Inheritance)

class Employee implements Salary, Tax {

String name;

int empId;

double basicSalary;

double grossSalary;

double taxAmount;

double netSalary;

Employee(int id, String name, double basicSalary) {

this.empId = id;

this.name = name;

this.basicSalary = basicSalary;

// From Salary interface

public void calculateSalary() {

double hra = 0.2 * basicSalary;


double da = 0.1 * basicSalary;

grossSalary = basicSalary + hra + da;

System.out.println("Gross Salary: ₹" + grossSalary);

// From Tax interface

public void calculateTax() {

taxAmount = 0.1 * grossSalary; // 10% tax

netSalary = grossSalary - taxAmount;

System.out.println("Tax Deducted: ₹" + taxAmount);

System.out.println("Net Salary: ₹" + netSalary);

public void displayDetails() {

System.out.println("Employee ID: " + empId);

System.out.println("Name: " + name);

System.out.println("Basic Salary: ₹" + basicSalary);

// Main class

public class Main {

public static void main(String[] args) {

Employee e1 = new Employee(101, "Rahul Mehta", 30000);

e1.displayDetails();

e1.calculateSalary();

e1.calculateTax();
}

—------------------------------------------------------------------------------------------------------------------

Nested Interface
✅ What is a Nested Interface in Java?
A nested interface is an interface declared within another class or interface.

Syntax :

class Outer
{
interface Inner
{
void show();
}
}

Example
// Outer interface
interface Vehicle {
void start();

// Nested interface inside interface


interface Engine {
void engineType();
}
}

// Class implementing the inner interface


class Car implements Vehicle.Engine
{
public void start()
{
System.out.println("Start Method");
}
public void engineType() {
System.out.println("Car has a Petrol Engine");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.engineType();
c.start();
}
}

—--------------------------------------------------------------------------------------

Chapter 3
Collection , Exception Handling and I/O

📚 What is Collection in Java?


In Java, a Collection is a framework that provides an architecture to
store and manipulate a group of objects. It is a part of the java.util
package and provides interfaces and classes to work with different types
of data structures such as lists, sets, queues, etc.

✅ Why Collections?
●​ Arrays are fixed in size and don’t offer many utility methods.​

●​ Collections are dynamic, flexible, and powerful.​

●​ Collections provide ready-to-use algorithms like sorting,


searching, etc.
Wrapper Classes

In Java, wrapper classes are used to convert primitive data types into
objects. Java provides a separate wrapper class for each primitive type,
and these classes are part of the java.lang package.

🧱 Wrapper Classes
Java is object-oriented, but primitive types like int, char, etc., are not
objects. So wrapper classes:

●​ Enable primitives to be used in collections (ArrayList, HashMap,


etc.)​

●​ Support object-oriented features like method calls​

●​ Provide utility methods (like parsing, conversion)

Primitive type Wrapper class


byte Byte
short Short
char Character
int Integer
long Long
float Float
double Double
boolean Boolean
Collection Framework
The Java Collections Framework (JCF) is a set of classes and
interfaces in the java.util package that provides ready-made data
structures (like List, Set, Map, Queue) and algorithms (like sorting,
searching, etc.) to store, access, and manipulate groups of objects
efficiently.

🎯 Goals of Collections Framework



Standardization

Provides standard interfaces and classes for data


structure implementation

✅ Code
Reusability

Ready-to-use classes reduce


boilerplate code


Efficiency

Provides optimized and well-tested


implementations

Extensibility

Easy to create your own data structure by


implementing interfaces

—---------------------------------------------------------

LIST Interface

In Java, the List interface is a part of the Collection framework and is


used to store an ordered collection of elements, including duplicates.
It is located in the java.util package and extends the Collection
interface.

✅ Key Features of List Interface


Feature Description
Ordered Collection Elements are stored in insertion
order
Indexed Access You can access elements using
indexes (like arrays)
Allows Duplicates Duplicate elements are allowed
Dynamic Resizing The size can grow or shrink as
needed
Null Values List can store null elements

Methods of List Interface


Method Description
void add(E obj) Adds an element to the end

void add(int index E obj) Adds an element at a specific


position
get(int index) Returns the element at the
specified index
set(int index, E element) Replaces element at specified
index
remove(int index) Removes element at specified
index
indexOf(Object o) Returns the index of the first
occurrence

lastIndexOf(Object o) Returns the last occurrence index

size() Returns the number of elements


isEmpty() Checks if the list is empty
contains(Object o) Checks if the list contains an
element
clear() Removes all elements

Implementations of List Interface


1. ArrayList
2 . LinkedList
3 . Vector

ArrayList
ArrayList is a class in the Java Collections Framework that implements
the List interface. It is part of the java.util package and provides a
resizable-array, which means it can grow and shrink dynamically as
elements are added or removed.

Declaration of ArrayList

ArrayList<Type> list = new ArrayList<>();

EX : ArrayList<String> names = new ArrayList<>();

Example :

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListFullExample {


public static void main(String[] args) {

ArrayList<String> colors = new ArrayList<>();

// 1. add(E e) - Add elements


colors.add("Red");
colors.add("Green");
colors.add("Blue");

// 2. add(int index, E element) - Insert at index


colors.add(1, "Yellow"); // Inserts Yellow at index 1

// 3. get(int index) - Get element at index


System.out.println("Element at index 2: " + colors.get(2)); // Output:
Green

// 4. set(int index, E element) - Replace element at index


colors.set(2, "Black"); // Replaces Green with Black
// 5. remove(int index) - Remove element by index
colors.remove(3); // Removes "Blue"

// 6. contains(Object o) - Check if element exists


System.out.println("Contains Red? " + colors.contains("Red")); // true

// 7. indexOf(Object o) - Get index of element


System.out.println("Index of Black: " + colors.indexOf("Black")); //
Output: 2

// 8. size() - Get size of list


System.out.println("Size of ArrayList: " + colors.size());

// 9. isEmpty() - Check if list is empty


System.out.println("Is list empty? " + colors.isEmpty()); // false

// 10. Iterating using iterator()


System.out.println("All colors:");
Iterator<String> it = colors.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

// 11. clear() - Remove all elements


colors.clear();

// Final check after clear


System.out.println("ArrayList after clear: " + colors); // Output: []
System.out.println("Is list empty now? " + colors.isEmpty()); // true
}
}

LinkedList
LinkedList is a class in the Java Collections Framework that
implements both the List and Deque interfaces. Unlike ArrayList,
which uses a dynamic array, LinkedList uses a doubly linked list to
store elements.

Declaration of LinkedList

LinkedList<Type> list = new LinkedList<>();

EX : LinkedList<String> cities = new LinkedList<>();

✅ When to Use ArrayList and LinkList


●​ Use ArrayList when you need fast access and don’t do
frequent insertions/removals.​

●​ Use LinkedList when your application involves frequent


insertions or deletions at the beginning or middle of
the list.​

Example :

import java.util.LinkedList;
import java.util.Iterator;

public class LinkedListExample {


public static void main(String[] args) {

LinkedList<String> cities = new LinkedList<>();


// 1. add() - Add elements to end
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Kolkata");

// 2. addFirst() - Add at beginning


cities.addFirst("Chennai");

// 3. addLast() - Add at end (same as add)


cities.addLast("Bangalore");

// 4. get() - Get element by index


System.out.println("City at index 2: " + cities.get(2)); // Mumbai

// 5. set() - Update element at index


cities.set(2, "Hyderabad");

// 6. remove() - Remove element by index


cities.remove(1); // Removes Chennai

// 7. removeFirst() - Remove first element


cities.removeFirst();

// 8. removeLast() - Remove last element


cities.removeLast();

// 9. contains() - Check if element exists


System.out.println("Contains Delhi? " + cities.contains("Delhi"));

// 10. indexOf() - Get index of element


System.out.println("Index of Hyderabad: " +
cities.indexOf("Hyderabad"));

// 11. size()
System.out.println("Size: " + cities.size());
// 12. isEmpty()
System.out.println("Is empty? " + cities.isEmpty());

// 13. Iterating with iterator()


System.out.println("Remaining Cities:");
Iterator<String> it = cities.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

// 14. clear()
cities.clear();
System.out.println("After clear: " + cities); // []
}
}

●​

Vector :

Vector is a legacy class in Java that implements the List interface and
uses a dynamic array to store elements, just like ArrayList.​
However, unlike ArrayList, Vector is synchronized — which means it is
thread-safe, but potentially slower in single-threaded environments.

Declaration:

Vector<Type> v = new Vector<>();

Vector<String> names = new Vector<>();


Example

import java.util.Vector;

import java.util.Iterator;

public class VectorExample {

public static void main(String[] args) {

// 1. Create a Vector

Vector<String> fruits = new Vector<>();

// 2. add(E e)

fruits.add("Apple");

fruits.add("Banana");

fruits.add("Cherry");

// 3. add(int index, E element)

fruits.add(1, "Mango");

// 4. get(int index)

System.out.println("Fruit at index 2: " + fruits.get(2)); // Banana

// 5. set(int index, E element)


fruits.set(2, "Grapes"); // Replaces Banana with Grapes

// 6. remove(int index)

fruits.remove(0); // Removes Apple

// 7. remove(Object o)

fruits.remove("Cherry"); // Removes Cherry

// 8. contains(Object o)

System.out.println("Contains Mango? " + fruits.contains("Mango"));

// 9. indexOf(Object o)

System.out.println("Index of Grapes: " + fruits.indexOf("Grapes"));

// 10. firstElement(), lastElement()

System.out.println("First: " + fruits.firstElement());

System.out.println("Last: " + fruits.lastElement());

// 11. size(), capacity()

System.out.println("Size: " + fruits.size());

System.out.println("Capacity: " + fruits.capacity());


// 12. isEmpty()

System.out.println("Is empty? " + fruits.isEmpty());

// 13. Iterator

System.out.println("All Fruits:");

Iterator<String> it = fruits.iterator();

while (it.hasNext()) {

System.out.println(it.next());

// 14. clear()

fruits.clear();

System.out.println("After clear: " + fruits); // []

System.out.println("Is empty after clear? " + fruits.isEmpty());

✅ Where to use
●​ 🔹 Use ArrayList when you want fast access and thread-safety is not a concern.​
●​ 🔹 Use LinkedList when frequent insertions/deletions in the middle are required.​
●​ 🔹 Use Vector if you need a synchronized, thread-safe list (or use
Collections.synchronizedList() instead of Vector for modern use).

SET Interface
The Set interface in Java is part of the Collection Framework and
represents a collection of unique elements. It does not allow duplicate
elements, unlike List.

1. HashSet

2 . TreeSet

3 . LinkedList

HashSet

HashSet is a class that implements the Set interface and is part of the
Java Collections Framework. It stores unique elements only and uses a
hash table for storage.

📘 Syntax:
HashSet<Type> setName = new HashSet<>();

EX : HashSet<String> cities = new HashSet<>();

toArray() : Returns an array containing all elements

retainAll(Collection<?>) : Retains only the elements also in another


collection

import java.util.HashSet;

import java.util.Iterator;
public class HashSetExample {

public static void main(String[] args) {

// Create a HashSet of Strings

HashSet<String> animals = new HashSet<>();

// add()

animals.add("Dog");

animals.add("Cat");

animals.add("Elephant");

animals.add("Dog"); // duplicate, won't be added

// size()

System.out.println("Size: " + animals.size()); // 3

// contains()

System.out.println("Contains 'Cat'? " + animals.contains("Cat"));


// true

// isEmpty()

System.out.println("Is Empty? " + animals.isEmpty()); // false

// iterator()
System.out.println("All animals:");

Iterator<String> it = animals.iterator();

while (it.hasNext()) {

System.out.println(it.next());

// remove()

animals.remove("Elephant");

// addAll()

HashSet<String> moreAnimals = new HashSet<>();

moreAnimals.add("Tiger");

moreAnimals.add("Lion");

animals.addAll(moreAnimals);

// retainAll()

HashSet<String> wildAnimals = new HashSet<>();

wildAnimals.add("Tiger");

wildAnimals.add("Lion");

animals.retainAll(wildAnimals); // keeps only tiger and lion


// toArray()

Object[] animalArray = animals.toArray();

System.out.println("Animals in Array:");

for (Object a : animalArray) {

System.out.println(a);

// removeAll()

animals.removeAll(wildAnimals);

// clear()

animals.clear();

System.out.println("After clear, size: " + animals.size());

2 . TreeSet

TreeSet is a class in Java that implements the Set interface and stores
unique elements in a sorted (ascending) order.

Syntax

TreeSet<Type> setName = new TreeSet<>();


TreeSet<Integer> numbers = new TreeSet<>();

import java.util.TreeSet;

public class TreeSetImportantMethods {

public static void main(String[] args) {

// Create a TreeSet of integers

TreeSet<Integer> set = new TreeSet<>();

// add() - Add elements

set.add(50);

set.add(20);

set.add(40);

set.add(10);

set.add(30);

// Display elements (sorted automatically)

System.out.println("TreeSet: " + set);

// first() and last()

System.out.println("First: " + set.first());

System.out.println("Last: " + set.last());


// contains()

System.out.println("Contains 40? " + set.contains(40)); // true

// remove()

set.remove(20);

System.out.println("After removing 20: " + set);

// pollFirst() and pollLast()

System.out.println("Poll First: " + set.pollFirst()); // removes 10

System.out.println("Poll Last: " + set.pollLast()); // removes 50

// Final set

System.out.println("Final TreeSet: " + set);

3. LinkedHashSet
LinkedHashSet is a class in Java that implements the Set interface and
stores unique elements in insertion order. It is a combination of HashSet
and LinkedList, internally using a hash table along with a doubly linked list
to maintain order.

Example :
import java.util.LinkedHashSet;

import java.util.Iterator;

public class LinkedHashSetExample {

public static void main(String[] args) {

// Create LinkedHashSet

LinkedHashSet<String> fruits = new LinkedHashSet<>();

// add()

fruits.add("Apple");

fruits.add("Banana");

fruits.add("Mango");

fruits.add("Orange");

fruits.add("Banana"); // Duplicate, will be ignored

// Display elements (insertion order)

System.out.println("Fruits: " + fruits);


// size()

System.out.println("Size: " + fruits.size());

// contains()

System.out.println("Contains Mango? " + fruits.contains("Mango"));

System.out.println("Contains Grape? " + fruits.contains("Grape"));

// isEmpty()

System.out.println("Is empty? " + fruits.isEmpty());

// iterator()

System.out.print("Using iterator: ");

Iterator<String> itr = fruits.iterator();

while (itr.hasNext()) {

System.out.print(itr.next() + " ");

System.out.println();

// remove()

fruits.remove("Orange");

System.out.println("After removing Orange: " + fruits);


// toArray()

Object[] array = fruits.toArray();

System.out.print("Array form: ");

for (Object obj : array) {

System.out.print(obj + " ");

System.out.println();

// clear()

fruits.clear();

System.out.println("After clear(), is empty? " + fruits.isEmpty());

MAP Interface
The Map interface in Java (from the java.util package) represents a
collection of key-value pairs where:

●​ Each key is unique​

●​ Each key maps to exactly one value


●​ Value Can be duplicated
●​ One null key allowed, multiple null values allowed (in
HashMap)

put(K key, V value) Adds key-value pair. If key exists,


updates value.

get(Object key) returns value for the key (or null if


not found).

remove(Object key) Removes mapping for the key.

boolean containsKey(Object key) Checks if key exists.

boolean containsValue(Object Checks if value exists.


value)

import java.util.*;

public class MapExample {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();


// put()

map.put(1, "Apple");

map.put(2, "Banana");

map.put(3, "Mango");

// get()

System.out.println("Value for key 2: " + map.get(2));

// containsKey() and containsValue()

System.out.println("Has key 1? " + map.containsKey(1));

System.out.println("Has value 'Banana'? " +


map.containsValue("Banana"));

// replace()

map.replace(2, "Banana", "Grapes");

System.out.println("After replace: " + map);

// getOrDefault()

System.out.println("Key 4 or default: " + map.getOrDefault(4, "Not


Found"));

// keySet()

System.out.println("Keys: " + map.keySet());


// values()

System.out.println("Values: " + map.values());

// entrySet()

System.out.println("Entries:");

for (Map.Entry<Integer, String> entry : map.entrySet()) {

System.out.println(entry.getKey() + " -> " + entry.getValue());

// remove()

map.remove(3);

System.out.println("After removing key 3: " + map);

// size() and isEmpty()

System.out.println("Size: " + map.size());

System.out.println("Is empty? " + map.isEmpty());

// clear()

map.clear();

System.out.println("After clear: " + map);

}
}

LinkHashMap : Key Points about LinkedHashMap


1.​Extends HashMap and implements Map interface.​

2.​Maintains a doubly-linked list across all entries — so it


remembers the order.​

3.​By default, it maintains the insertion order.​

4.​It can also maintain access order

example
import java.util.LinkedHashMap;

import java.util.Map;

public class LinkedHashMapExample {

public static void main(String[] args) {

// Creating LinkedHashMap

LinkedHashMap<Integer, String> students = new


LinkedHashMap<>();

// Adding entries
students.put(101, "Alice");

students.put(102, "Bob");

students.put(103, "Charlie");

students.put(104, "Daisy");

// Accessing elements

System.out.println("Student Map:");

for (Map.Entry<Integer, String> entry : students.entrySet()) {

System.out.println("Roll No: " + entry.getKey() + ", Name: " +


entry.getValue());

// Checking insertion order maintained

System.out.println("\nInsertion Order Maintained:");

System.out.println(students); // Output will show keys in the


same order as inserted

// Accessing value by key

System.out.println("\nStudent with Roll No 102: " +


students.get(102));

// Removing an entry
students.remove(103);

System.out.println("\nAfter removing Roll No 103:");

System.out.println(students);

TreeMap
TreeMap is a part of Java’s java.util package and implements
the Map interface. It stores key-value pairs just like HashMap, but
the keys are sorted in natural order (ascending) or according to a
provided Comparator.

✅ Key Features of TreeMap:


●​ Stores elements in sorted order of keys.​

●​ No duplicate keys allowed.​

●​ Allows null values, but not null keys.​

●​ Is not synchronized (not thread-safe by default).​

Syntax:

TreeMap<KeyType, ValueType> mapName = new


TreeMap<>();
Example :

import java.util.*;

public class TreeMapExample {

public static void main(String[] args) {

// Create TreeMap

TreeMap<Integer, String> studentMap = new TreeMap<>();

// Add entries

studentMap.put(102, "Alice");

studentMap.put(101, "Bob");

studentMap.put(104, "Charlie");

studentMap.put(103, "David");

// Display TreeMap (automatically sorted by key)

System.out.println("Student Records (sorted by ID):");

for (Map.Entry<Integer, String> entry :


studentMap.entrySet()) {

System.out.println("ID: " + entry.getKey() + ", Name: " +


entry.getValue());
}

// Get specific value

System.out.println("\nStudent with ID 102: " +


studentMap.get(102));

// Remove an entry

studentMap.remove(101);

System.out.println("\nAfter removing ID 101: " +


studentMap);

// Check if key/value exists

System.out.println("Contains key 103? " +


studentMap.containsKey(103));

System.out.println("Contains value 'Charlie'? " +


studentMap.containsValue("Charlie"));

// Get first and last keys

System.out.println("First Key: " + studentMap.firstKey());

System.out.println("Last Key: " + studentMap.lastKey());

// SubMap example
System.out.println("SubMap from 102 to 104: " +
studentMap.subMap(102, 104));

Use TreeMap when:

●​ You need a sorted map by keys.

HashTable
The Hashtable class is part of the Java Collection Framework and
implements the Map interface. It stores key-value pairs just like
HashMap, but it is synchronized, making it thread-safe.

✅ Key Features of Hashtable:


●​ Synchronized: Thread-safe (unlike HashMap).​

●​ No null keys or values allowed.​

●​ Keys are unique.​

●​ Unordered: Does not maintain any order of keys or values.​

●​ Slower than HashMap due to synchronization.


Hashtable<KeyType, ValueType> hashtableName = new
Hashtable<>();

Example :

import java.util.*;

public class HashtableExample {

public static void main(String[] args) {

// Create a Hashtable

Hashtable<Integer, String> employeeTable = new Hashtable<>();

// Add key-value pairs

employeeTable.put(101, "Alice");

employeeTable.put(102, "Bob");

employeeTable.put(103, "Charlie");

// Display the Hashtable

System.out.println("Employee Records:");

for (Map.Entry<Integer, String> entry : employeeTable.entrySet())


{

System.out.println("ID: " + entry.getKey() + ", Name: " +


entry.getValue());
}

// Get a value

System.out.println("\nEmployee with ID 102: " +


employeeTable.get(102));

// Remove an entry

employeeTable.remove(101);

System.out.println("\nAfter removing ID 101: " + employeeTable);

// Check if key/value exists

System.out.println("Contains key 103? " +


employeeTable.containsKey(103));

System.out.println("Contains value 'Alice'? " +


employeeTable.containsValue("Alice"));

// Replace value

employeeTable.replace(103, "David");

System.out.println("After replacing value at ID 103: " +


employeeTable);

}
●​ Use Hashtable only if you need thread-safety in a
multi-threaded environment.​

●​ Otherwise, HashMap is generally preferred for performance.​

1. Iterator in Java

1.Used to traverse elements of any Collection (List, Set,


etc.).​

2.Can remove elements during iteration.​

3.Forward-only traversal.

Methods:
●​ hasNext(): Returns true if there are more elements.​

●​ next(): Returns the next element.​

●​ remove(): Removes current element (optional operation).

EX
import java.util.*;

public class IteratorExample {

public static void main(String[] args) {

List<String> fruits = new ArrayList<>();

fruits.add("Apple");

fruits.add("Banana");

fruits.add("Mango");

Iterator<String> it = fruits.iterator();

System.out.println("Using Iterator:");

while (it.hasNext()) {

String fruit = it.next();

System.out.println(fruit);

if (fruit.equals("Banana")) {

it.remove(); // Remove "Banana"

}
System.out.println("After removal: " + fruits);

2. ListIterator in Java

1.Used to traverse only List implementations.​

2.Supports both forward and backward traversal.​

3.Can add, remove, and modify elements during iteration.

Methods:

●​ hasNext(), next()​

●​ hasPrevious(), previous()​

●​ add(E e), remove(), set(E e)

import java.util.*;
public class ListIteratorExample {

public static void main(String[] args) {

List<String> names = new ArrayList<>();

names.add("Amit");

names.add("Rahul");

names.add("Sneha");

ListIterator<String> listIt = names.listIterator();

System.out.println("Forward Traversal:");

while (listIt.hasNext()) {

System.out.println(listIt.next());

System.out.println("Backward Traversal:");

while (listIt.hasPrevious()) {

System.out.println(listIt.previous());

}
// Modify during iteration

listIt = names.listIterator();

while (listIt.hasNext()) {

String name = listIt.next();

if (name.equals("Rahul")) {

listIt.set("Raj"); // Modify

System.out.println("Modified List: " + names);

3. Enumeration in Java

●​ Legacy iterator for Vector and Hashtable.​

●​ Forward-only, read-only traversal (no remove or update).​

●​ Used before Iterator was introduced.


●​ Enumeration is an interface in Java that was introduced in JDK
1.0 and is used to iterate over legacy collection classes like
Vector, Stack, and Hashtable. It is part of the java.util package
●​ It is read-only, meaning you can only traverse elements, not
modify or remove them.

Methods:

●​ hasMoreElements()​

●​ nextElement()

import java.util.*;

public class EnumerationExample {

public static void main(String[] args) {

Vector<String> colors = new Vector<>();

colors.add("Red");

colors.add("Green");

colors.add("Blue");

Enumeration<String> e = colors.elements();

System.out.println("Using Enumeration:");

while (e.hasMoreElements()) {

System.out.println(e.nextElement());

}
}

—------------------------------------------------------------------------------------
-

What is an Exception in Java?


●​ An Exception is an unwanted or unexpected event that
occurs during the execution of a program and disrupts its
normal flow.

Types of Exceptions

1.​Checked Exceptions​

○​ Checked at compile-time.​

○​ The programmer must handle them using try-catch


or declare them using throws.​

○​ Example: IOException, SQLException.​

2.​Unchecked Exceptions (Runtime Exceptions)​

○​ Occur during runtime, not checked at compile-time.​

○​ Example: ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException.​
3.​Errors​

○​ Serious issues beyond the control of programmers.​

○​ Example: OutOfMemoryError,
StackOverflowError.​

○​ Usually not handled in programs.

Exception Handling in Java


●​ Exception handling is the mechanism to handle runtime
errors so that the normal flow of the application can be
maintained.​

Why do we need it?

●​ To prevent program crashes.​

●​ To handle errors gracefully.​

●​ To provide meaningful messages to users instead of abrupt


termination.​

Exception Handling Keywords

1.​try → block of code where exception may occur.​


2.​catch → block to handle the exception.​

3.​finally → block that always executes (cleanup code).​

4.​throw → used to explicitly throw an exception.​

5.​throws → used in method declaration to specify exceptions


a method can throw.

Exception Class in Java

In Java, Exception is a class that represents conditions a


program might want to catch.​
It is a subclass of Throwable, which means all exceptions are
objects of type Exception (or its subclasses).

# Every exception in Java is an object derived from the


Exception class.#

Exception Handling

1. try-catch Example (Unchecked Exception)

Example

public class Example1 {

public static void main(String[] args) {

try {

int a = 10, b = 0;
int c = a / b; // Will throw ArithmeticException

System.out.println("Result: " + c);

catch (ArithmeticException e) // Exception e

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

2. try-catch-finally Example
Example
public class Example2 {

public static void main(String[] args) {

try {

String str = null;

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

} catch (NullPointerException e) {

System.out.println("Null Pointer Exception caught.");


} finally {

System.out.println("Finally block always executes.");

Nested Try-Catch/Multiple catch

Ex
public class NestedTryExample {

public static void main(String[] args) {

try {

// Outer try block

int[] arr = new int[3];

try {

// Inner try block

int x = 10 / 0; // Causes ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Inner catch: Arithmetic Exception - " +


e.getMessage());

}
arr[5] = 100; // Causes ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Outer catch: Array Index Exception - " +


e.getMessage());

System.out.println("Program continues...");

throw Keyword (Used to explicitly throw an exception)

●​ The throw keyword is used to manually throw an exception in Java.​

●​ It is used within a method or block.​

●​ You can throw only one exception at a time.​

●​ Syntax:

​ throw new ExceptionType("Error Message");

🔷 throws Keyword (Used to declare exceptions)


●​ The throws keyword is used to declare exceptions that a
method might throw.​

●​ It appears in the method signature.​

●​ Syntax:

​ returnType methodName() throws ExceptionType1, ExceptionType2 { ... }

🔁 Difference Between throw and throws


throw throws
Used to explicitly throw an Used to declare exceptions a
exception method might throw

Occurs inside a method Appears in the method


signature

Can only throw one exception Can declare multiple


exceptions

Follows throw new Follows method declaration


Exception()

Example: throw Keyword

public class ThrowExample {

public static void main(String[] args) {

int age = 16;


if (age < 18) {

throw new ArithmeticException("Not eligible to


vote");

System.out.println("You can vote!");

Example: throws Keyword

import java.io.*;

public class ThrowsExample {

// Method declares that it might throw IOException

public static void readFile(String filename) throws


IOException {

FileReader fr = new FileReader(filename); // File


may not exist

BufferedReader br = new BufferedReader(fr);

System.out.println(br.readLine());

br.close();
}

public static void main(String[] args) {

try {

readFile("test.txt"); // File doesn't exist

} catch (IOException e) {

System.out.println("Handled Exception: " +


e.getMessage());

Example Using Both throw and throws

class CustomExceptionExample {

// Method declares it may throw Exception

static void checkNumber(int num) throws Exception {

if (num < 0) {

// Throwing exception manually

throw new Exception("Number can't be negative");

} else {

System.out.println("Valid number: " + num);


}

public static void main(String[] args) {

try {

checkNumber(-10); // Will throw exception

} catch (Exception e) {

System.out.println("Caught Exception: " +


e.getMessage());

User Defined Exception

In Java, user-defined exceptions allow you to create your


own exception classes that extend either Exception or
RuntimeException. By doing this, you can throw and catch
exceptions that are specific to your application's needs.

Steps to Create a User-Defined Exception in Java:

1.​Create a custom exception class by extending Exception


or RuntimeException.​
2.If you extend Exception, it is a checked exception, and
the caller must handle it (either with try-catch or by
declaring it in the method signature using throws).​

3.If you extend RuntimeException, it is an unchecked


exception, which means the caller is not required to handle it.

4.Define a constructor to pass custom error messages or


values.​

5.Throw the exception in your program where necessary


using throw.​

6.Catch the exception using a try-catch block.

Example :

import java.util.Scanner;

// User-defined exception class

class InvalidAgeException extends Exception {

private int age;

// Constructor with custom message

public InvalidAgeException(int age) {


super("Invalid age: Age must be a positive
number.");

this.age = age;

// Getter to retrieve the invalid age

public int getAge() {

return age;

public class AgeValidator {

// Method to validate the age

public static void setAge(int age) throws


InvalidAgeException {

if (age <= 0) {

throw new InvalidAgeException(age);

} else {

System.out.println("Age set to " + age + "


years.");

}
}

// Main method

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your age: ");

int age = scanner.nextInt();

try {

setAge(age);

} catch (InvalidAgeException e) {

System.out.println("Error: " + e.getMessage() +


" Invalid age entered: " + e.getAge());

} finally {

scanner.close();

}
String Class in java
The String class in Java is one of the most commonly used
classes, as it represents a sequence of characters. Java
provides a rich set of methods in the String class to
manipulate strings. Understanding these methods is essential
for working with text data in Java.

Key Points about the String Class:

●​ Immutable: The String class is immutable, which means that


once a string object is created, its value cannot be
changed. Any operation that modifies a string actually
creates a new string.​

●​ String Pool: Strings in Java are stored in a special memory


area known as the string pool. If two string literals have
the same value, they will refer to the same object in the
pool.

Example :

public class StringImmutableExample {

public static void main(String[] args) {

String s1 = "Hello";

// Modify string

String s2 = s1.concat(" World");


System.out.println("s1: " + s1); // "Hello"

System.out.println("s2: " + s2); // "Hello World"

// Checking references

System.out.println(s1 == s2); // false (different


objects)

🔹 1. length()
Description: Returns the length of the string (number of
characters).​
Example: "Java".length() → 4

🔹 2. charAt(int index)
Description: Returns the character at the specified index.​
Example: "Java".charAt(1) → 'a'

🔹 3. substring(int startIndex)
Description: Returns a substring from the specified index to
the end.​
Example: "Java".substring(2) → "va"

🔹 4. substring(int startIndex, int endIndex)


Description: Returns a substring from startIndex to endIndex
- 1.​
Example: "Java".substring(1, 3) → "av"

🔹 5. toLowerCase()
Description: Converts all characters to lowercase.​
Example: "JAVA".toLowerCase() → "java"

🔹 6. toUpperCase()
Description: Converts all characters to uppercase.​
Example: "java".toUpperCase() → "JAVA"

🔹 7. equals(String anotherString)
Description: Compares two strings for equality
(case-sensitive).​
Example: "Java".equals("Java") → true

🔹 8. equalsIgnoreCase(String anotherString)
Description: Compares two strings for equality
(case-insensitive).​
Example: "Java".equalsIgnoreCase("java") → true

🔹 9. compareTo(String anotherString)
Description: Compares two strings.​
Example: "apple".compareTo("banana") → -1

🔹 10. compareToIgnoreCase(String anotherString)


Description: Lexicographically compares two strings ignoring
case.​
Example: "Apple".compareToIgnoreCase("apple") → 0

🔹 11. contains(CharSequence sequence)


Description: Checks if the string contains the given
sequence.​
Example: "Hello World".contains("World") → true

🔹 12. startsWith(String prefix)


Description: Checks if the string starts with the specified
prefix.​
Example: "Hello".startsWith("He") → true
🔹 13. endsWith(String suffix)
Description: Checks if the string ends with the specified
suffix.​
Example: "Hello".endsWith("lo") → true

🔹 14. isEmpty()
Description: Returns true if the string is empty (length()
== 0).​
Example: "".isEmpty() → true

🔹 15. trim()
Description: Removes leading and trailing spaces.​
Example: " Java ".trim() → "Java"

🔹 16. indexOf(String str)


Description: Returns the index of the first occurrence of
the specified substring.​
Example: "Programming".indexOf("g") → 3

🔹 17. lastIndexOf(String str)


Description: Returns the last index of the specified
substring.​
Example: "Programming".lastIndexOf("g") → 10
🔹 18. replace(char oldChar, char newChar)
Description: Replaces all occurrences of the specified
character.​
Example: "apple".replace('p', 'b') → "abble"

🔹 19. replace(CharSequence target, CharSequence


replacement)

Description: Replaces all occurrences of a substring with


another.​
Example: "Java is fun".replace("fun", "powerful") → "Java
is powerful"

🔹 20. split(String regex)


Description: Splits the string based on the specified
regular expression.​
Example: "a,b,c".split(",") → ["a", "b", "c"]

🔹 21. concat(String str)


Description: Concatenates the specified string.​
Example: "Hello".concat(" World") → "Hello World"

🔹 22. valueOf(anyType)
Description: Converts any type (int, float, etc.) to a
string.​
Example: String.valueOf(100) → "100"

🔹 23. toCharArray()
Description: Converts string to a character array.​
Example: "Java".toCharArray() → ['J', 'a', 'v', 'a']

🔹 26. matches(String regex)


Description: Checks if the string matches the given regular
expression.​
Example: "abc123".matches("[a-z]+\\d+") → true

StringBuffer class in Java

The StringBuffer class in Java is used to create mutable


(modifiable) strings. Unlike the String class (which is
immutable), a StringBuffer can be modified without creating a
new object.

Why do we need StringBuffer?

●​ String is immutable → Any modification creates a new


object → Memory inefficient​

●​ StringBuffer is mutable → Changes happen in the same


object → Efficient for repeated string manipulation
EXAMPLE :

public class StringBufferExample {

public static void main(String[] args) {

// Constructor

StringBuffer sb = new StringBuffer("Hello");

// 1. append(String str)

sb.append(" World"); // adds at the end

System.out.println("append(): " + sb); // Hello


World

// 2. insert(int offset, String str)

sb.insert(6, "Java ");

System.out.println("insert(): " + sb); // Hello Java


World

// 3. replace(int start, int end, String str)

sb.replace(6, 10, "C++");

System.out.println("replace(): " + sb); // Hello C++


World
// 4. delete(int start, int end)

sb.delete(6, 10);

System.out.println("delete(): " + sb); // Hello


World

// 5. reverse()

sb.reverse();

System.out.println("reverse(): " + sb); // dlroW


olleH

// 6. length()

System.out.println("length(): " + sb.length()); //


12

// 7. capacity()

System.out.println("capacity(): " + sb.capacity());


// default is 16 + string length

// 8. setCharAt(int index, char ch)

sb.setCharAt(0, 'D');
System.out.println("setCharAt(): " + sb); // DlroW
olleH

// 9. charAt(int index)

System.out.println("charAt(1): " + sb.charAt(1)); //


l

// 10. ensureCapacity(int minimumCapacity)

sb.ensureCapacity(100);

System.out.println("ensureCapacity(100): " +
sb.capacity()); // may be >= 100

// 11. substring(int start)

System.out.println("substring(2): " +
sb.substring(2)); // roW olleH

// 12. substring(int start, int end)

System.out.println("substring(2, 5): " +


sb.substring(2, 5)); // roW

—----------------------------------------------------------
File Class :

The File class in Java is part of the java.io package and is


used to represent the pathnames of files and directories.

It does not deal with the contents of the file directly


(like reading or writing). Instead, it provides methods to
create, delete, and obtain information (metadata) about
files and directories.

Key Points about File Class


●​ Belongs to java.io package → import java.io.File;​

●​ Represents files and directories (folders).​

●​ Can be used to create new files/directories.​

●​ Provides methods to check file properties like


readability, writability, existence, length, etc.​

●​ Does not read/write content directly (for that, use


FileReader, FileWriter, FileInputStream,
FileOutputStream, etc.).

Constructors
1.​File(String pathname) → Creates a file object using
pathname.​
Example: File f = new File("data.txt");​

2.​File(String parent, String child) → Creates file object


from parent directory and child file.​
Example: File f = new File("C:\\Users\\Sunil",
"data.txt");​

3.​File(File parent, String child) → Same as above, but


parent as a File object.​
Example:

Example :

File dir = new File("C:\\Users\\Sunil");

File f = new File(dir, "data.txt");

Important Methods of File Class

Method Description

boolean Creates a new, empty file. Returns


createNewFile() true if successful.

boolean exists() Checks if file/directory exists.

boolean delete() Deletes file/directory.


String getName() Returns file/directory name.

String Returns absolute pathname.


getAbsolutePath()

String getPath() Returns path used while creating


object.

boolean isFile() Checks if path is a file.

boolean Checks if path is a directory.


isDirectory()

boolean canRead() Checks if file is readable.

boolean canWrite() Checks if file is writable.

long length() Returns length of file in bytes.

String[] list() Lists files and directories inside


a directory.

File[] listFiles() Same as above, but returns File


objects.
boolean mkdir() Creates a new directory.

boolean mkdirs() Creates directory including all


parent dirs if not exist.

Example

import java.io.File;

import java.io.IOException;

public class FileMethodExample {

public static void main(String[] args) throws IOException {

File f = new File("demo.txt");

if (f.createNewFile()) {

System.out.println("File created.");

} else {

System.out.println("File already exists.");

System.out.println("Name: " + f.getName());


System.out.println("Path: " + f.getPath());

System.out.println("Absolute Path: " +


f.getAbsolutePath());

System.out.println("Writable: " + f.canWrite());

System.out.println("Readable: " + f.canRead());

System.out.println("Executable: " + f.canExecute());

System.out.println("Is File: " + f.isFile());

System.out.println("Is Directory: " + f.isDirectory());

System.out.println("Length: " + f.length() + " bytes");

// Rename

File newFile = new File("renamed.txt");

if (f.renameTo(newFile)) {

System.out.println("Renamed to: " +


newFile.getName());

// Delete

if (newFile.delete()) {

System.out.println("Deleted file.");

}
}

FileInputStream

FileInputStream is a class in the java.io package used to


read raw byte data from a file. It is typically used for:

●​ Reading binary files (e.g., images, audio, PDFs)​

●​ Reading text files (not recommended for character data


– use FileReader instead)

FileOutputStream in Java

FileOutputStream is a class in the java.io package used to


write raw bytes to a file. It is mainly used for writing
binary data (like images, PDFs), but can also write text
data if converted to bytes.

Example

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileStreamExample {

public static void main(String[] args) throws IOException {

// Step 1: Write to a file using FileOutputStream


FileOutputStream fos = new
FileOutputStream("sample.txt");

String text = "Hello, Java File Streams!";

byte[] data = text.getBytes(); // Convert string to


byte array

fos.write(data); // Write byte array to


file

fos.close(); // Close output stream

// Step 2: Read from the same file using FileInputStream

FileInputStream fis = new FileInputStream("sample.txt");

int byteData;

System.out.println("File content read using


FileInputStream:");

while ((byteData = fis.read()) != -1) {

System.out.print((char) byteData); // Convert byte


to char and print

fis.close(); // Close input stream

}
FileReader in Java?

FileReader is a class in the java.io package used to read


character data from files. It is a convenience class built
on top of InputStreamReader that simplifies reading text
files.

Key Features:

●​ Designed specifically for reading character files (not


binary files).​

●​ Reads data character by character.

Example

import java.io.FileReader;

import java.io.IOException;

public class FileReaderExample {

public static void main(String[] args) throws


IOException {

FileReader fr = new FileReader("message.txt");


int ch;

System.out.println("Reading from file:");

// Read and print characters one by one

while ((ch = fr.read()) != -1) {

System.out.print((char) ch);

fr.close();

FileWriter in Java?

FileWriter is a class in the java.io package used to write


character data to files. It is a character-oriented stream,
meaning it is best suited fo

r writing text rather than binary data.

✅ Key Features:
●​ Writes characters (char data) to a file.​
●​ Automatically converts characters to bytes using the
platform’s default character encoding.​

●​ Creates a new file if it does not exist.

Example

import java.io.FileWriter;

import java.io.IOException;

public class FileWriterExample {

public static void main(String[] args) throws IOException {

// Create a FileWriter object to write to file.txt

FileWriter fw = new FileWriter("file.txt");

// Write text to file

fw.write("Hello, this is written using FileWriter in


Java!");

// Always close the stream

fw.close();

System.out.println("Data written successfully.");

}
}

DataInputStream and DataOutputStream in Java?

DataInputStream and DataOutputStream are byte stream classes


from the java.io package used to read and write primitive data
types (int, float, double, char, boolean, etc.) in a
machine-independent way.

These classes are used when you need to write binary data
instead of plain text.

Why Use Them?


Java’s basic InputStream and OutputStream read and write
bytes. If you want to read/write structured data (like int,
float, boolean, etc.), then DataInputStream/DataOutputStream
provide that support with methods like writeInt(),
readInt(), etc.

Example ​

import java.io.*;

public class DataStreamExample {

public static void main(String[] args) throws IOException {


// Step 1: Write data to a binary file

DataOutputStream dos = new DataOutputStream(new


FileOutputStream("data.bin"));

dos.writeInt(101);

dos.writeDouble(99.99);

dos.writeUTF("Hello Data Stream");

dos.writeBoolean(true);

dos.writeChar('A');

dos.close(); // Close output stream

// Step 2: Read data back from the binary file

DataInputStream dis = new DataInputStream(new


FileInputStream("data.bin"));

int id = dis.readInt();

double price = dis.readDouble();

String message = dis.readUTF();

boolean status = dis.readBoolean();

char grade = dis.readChar();


dis.close(); // Close input stream

// Display the data

System.out.println("ID: " + id);

System.out.println("Price: " + price);

System.out.println("Message: " + message);

System.out.println("Status: " + status);

System.out.println("Grade: " + grade);

—-----------------------------------------------------------

You might also like