# ☕ Java Revision — README

---

# 1️⃣ Java Fundamentals — Revision

## 1.1 Java Overview

### 📖 What is Java?

Java is a **high-level, object-oriented, class-based, platform-independent programming language**.

### ✨ Key Features

- Object-Oriented
- Platform Independent
- Robust
- Secure
- Multithreaded
- Portable
- Automatic Memory Management

### 🔄 Basic Flow

```text
Java Source Code
      ↓
   Compiler
      ↓
   Bytecode
      ↓
     JVM
      ↓
Operating System
```

### 🧠 Easy Remember

> **Write Once, Run Anywhere (WORA)**

---

## 1.2 JDK, JRE, JVM

### 🖥️ JVM — Java Virtual Machine

- Executes Java bytecode.
- Provides platform independence.

### 🌐 JRE — Java Runtime Environment

- Provides the environment required to run Java applications.
- Contains JVM + runtime libraries.

### 🛠️ JDK — Java Development Kit

- Used to develop Java applications.
- Contains JRE + development tools such as the Java compiler.

### 🔗 Relationship

```text
JDK
 └── JRE
      └── JVM
```

### 🧠 Easy Remember

> **JDK → Develop**  
> **JRE → Run**  
> **JVM → Execute**

---

## 1.3 Java Compilation & Execution

### 🔄 Steps

```text
Hello.java
    ↓
javac Hello.java
    ↓
Hello.class
    ↓
JVM
    ↓
Program Execution
```

### 💻 Example

```java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello Java");
    }
}
```

### 📌 Important Terms

- `.java` → Source code
- `javac` → Java compiler
- `.class` → Bytecode
- `java` → Runs the compiled program
- JVM → Executes bytecode

---

# 1.4 Variables

### 📖 What is a Variable?

A variable is a **named memory location used to store data**.

```java
int age = 20;
String name = "Ravi";
```

### 🧩 Types of Variables

#### 1. Local Variable

Declared inside a method, constructor, or block.

```java
void display() {
    int age = 20;
}
```

#### 2. Instance Variable

Declared inside a class but outside methods, without `static`.

```java
class Student {
    String name;
}
```

#### 3. Static Variable

Declared using `static` and belongs to the class.

```java
class Student {
    static String college = "ABC College";
}
```

---

# 1.5 Data Types

Java data types are divided into:

```text
Data Types
├── Primitive
└── Non-Primitive / Reference
```

## 🔢 Primitive Data Types

| Type      | Example             |
| --------- | ------------------- |
| `byte`    | `byte x = 10;`      |
| `short`   | `short x = 100;`    |
| `int`     | `int x = 1000;`     |
| `long`    | `long x = 10000L;`  |
| `float`   | `float x = 10.5f;`  |
| `double`  | `double x = 10.5;`  |
| `char`    | `char x = 'A';`     |
| `boolean` | `boolean x = true;` |

## 🧱 Reference Types

Examples:

- String
- Arrays
- Classes
- Interfaces
- Objects
- Enums

```java
String name = "Ravi";
int[] numbers = {10, 20, 30};
```

### 🧠 Easy Remember

**Primitive → stores basic values**

**Reference → stores a reference to an object**

---

# 1.6 Type Casting

### 📖 What is Type Casting?

Converting a value from one data type to another.

### 🧩 Types

```text
Type Casting
├── Widening
└── Narrowing
```

### 1. Widening Casting

Smaller type → Larger type

**Automatic**

```java
int x = 10;
double y = x;
```

```text
int → long → float → double
```

### 2. Narrowing Casting

Larger type → Smaller type

**Manual**

```java
double x = 10.5;
int y = (int) x;
```

Output:

```text
10
```

⚠️ Data may be lost during narrowing.

---

# 1.7 Operators

Operators are symbols used to perform operations on values.

### 🧩 Types of Operators

```text
Operators
├── Arithmetic
├── Relational
├── Logical
├── Assignment
├── Unary
├── Bitwise
├── Ternary
└── Shift
```

### ➕ Arithmetic

```java
+  -  *  /  %
```

```java
int result = 10 + 5;
```

### ⚖️ Relational

```java
==  !=  >  <  >=  <=
```

```java
age >= 18
```

Returns `true` or `false`.

### 🔗 Logical

```java
&&   ||   !
```

```java
age >= 18 && hasId
```

### 📝 Assignment

```java
=   +=   -=   *=   /=   %=
```

```java
int x = 10;
x += 5;
```

### 🔁 Unary

```java
++   --   +   -
```

```java
x++;
```

### ❓ Ternary

```java
condition ? value1 : value2
```

```java
int result = age >= 18 ? 1 : 0;
```

### 🧮 Bitwise / Shift

```java
&   |   ^   ~
<<  >>  >>>
```

Used mainly for **bit-level operations**.

---

# 1.8 Conditional Statements

Used to make decisions in a program.

### 🧩 Types

```text
Conditional Statements
├── if
├── if-else
├── else-if
└── switch
```

### if

```java
if (age >= 18) {
    System.out.println("Adult");
}
```

### if-else

```java
if (age >= 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}
```

### else-if

```java
if (mark >= 90) {
    System.out.println("A");
} else if (mark >= 75) {
    System.out.println("B");
} else {
    System.out.println("C");
}
```

### switch

Used when comparing one value against multiple cases.

```java
switch (day) {
    case 1:
        System.out.println("Monday");
        break;

    case 2:
        System.out.println("Tuesday");
        break;

    default:
        System.out.println("Invalid");
}
```

---

# 1.9 Loops

Used to execute a block of code repeatedly.

### 🧩 Types

```text
Loops
├── for
├── while
├── do-while
└── enhanced for (for-each)
```

### for

Used when the number of iterations is generally known.

```java
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
```

### while

Used when the condition is checked before each iteration.

```java
while (condition) {
    // code
}
```

### do-while

Executes the block **at least once**.

```java
do {
    // code
} while (condition);
```

### Enhanced for / for-each

Commonly used with arrays and collections.

```java
for (int number : numbers) {
    System.out.println(number);
}
```

### 🚦 Loop Control

- `break` → exits the loop
- `continue` → skips the current iteration

---

# 1.10 Arrays

### 📖 What is an Array?

An array stores **multiple values of the same data type** in a fixed-size structure.

```java
int[] numbers = {10, 20, 30, 40};
```

### ✨ Features

- Fixed size
- Same data type
- Zero-based indexing
- Can store primitive or reference values

### Accessing Elements

```java
System.out.println(numbers[0]);
```

Output:

```text
10
```

### Array Length

```java
System.out.println(numbers.length);
```

### 🧩 Types

```text
Arrays
├── One-Dimensional
└── Multidimensional
```

### One-Dimensional

```java
int[] numbers = {10, 20, 30};
```

### Two-Dimensional

```java
int[][] matrix = {
    {1, 2},
    {3, 4}
};
```

### 📌 Important Point

Array indexing starts from **0**.

```text
numbers = {10, 20, 30}

index →   0   1   2
value →  10  20  30
```

---

## 🔁 Quick Revision — Java Fundamentals

```text
Java
│
├── Java Overview
├── JDK / JRE / JVM
├── Compilation & Execution
├── Variables
├── Data Types
├── Type Casting
├── Operators
├── Conditional Statements
├── Loops
└── Arrays
```

### 🧠 Must Remember

- **JDK → Develop**
- **JRE → Run**
- **JVM → Execute**
- **Primitive → Basic values**
- **Widening → Automatic**
- **Narrowing → Manual**
- **if / switch → Decision**
- **Loops → Repetition**
- **Array → Fixed-size collection of same type**
- **Array index starts at 0**

---

# 2️⃣ Object-Oriented Programming

## 2.1 Classes & Objects

### 📖 What is a Class?

A class is a blueprint/template used to create objects.

It defines:

- Data → Fields / Variables
- Behavior → Methods

```java
class Student {
    String name;
    int age;

    void study() {
        System.out.println("Student is studying");
    }
}
```

### 📖 What is an Object?

An object is an instance of a class.

```java
Student s1 = new Student();

s1.name = "Ravi";
s1.age = 20;

s1.study();
```

### 🏠 Easy Analogy

Think about a house blueprint.

```text
Class  → Blueprint
Object → Actual House
```

One class can create multiple objects.

```java
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
```

```text
Student Class
     │
     ├── s1
     ├── s2
     └── s3
```

Each object can have its own data.

### 📌 Important Terms

- Class → Blueprint
- Object → Instance
- Field → Data/State
- Method → Behavior
- `new` → Creates an object

---

## 2.2 Constructors

### 📖 What is a Constructor?

A constructor is a special member of a class used to initialize an object.

### Rules

- Same name as the class
- No return type
- Automatically called when an object is created
- Can be overloaded

```java
class Student {

    String name;
    int age;

    Student() {
        name = "Unknown";
        age = 0;
    }
}
```

Creating the object:

```java
Student s1 = new Student();
```

The constructor is automatically called.

### 🧩 Types of Constructors

```text
Constructors
├── Default Constructor
├── No-Argument Constructor
└── Parameterized Constructor
```

### No-Argument Constructor

```java
Student() {
    name = "Unknown";
}
```

### Parameterized Constructor

```java
Student(String name, int age) {
    this.name = name;
    this.age = age;
}
```

Usage:

```java
Student s1 = new Student("Ravi", 20);
```

### Constructor Overloading

Multiple constructors with different parameters.

```java
class Student {

    Student() {
    }

    Student(String name) {
    }

    Student(String name, int age) {
    }
}
```

### ⚖️ Constructor vs Method

| Constructor                                 | Method                    |
| ------------------------------------------- | ------------------------- |
| Initializes object                          | Performs an operation     |
| Same name as class                          | Can have any valid name   |
| No return type                              | Has a return type or void |
| Called automatically during object creation | Called explicitly         |
| Cannot be inherited                         | Can be inherited          |

### 🧠 Easy Remember

- Class = Blueprint
- Object = Real thing
- Constructor = Object initialization

---

## 2.3 Encapsulation

### 📖 What is Encapsulation?

Encapsulation is the process of bundling data and methods together inside a class and controlling direct access to the data.

### 🏧 Simple Analogy

Think of an ATM.

You can interact with your bank account through:

- Withdraw
- Deposit
- Check Balance

But you cannot directly access or modify the bank's internal data.

```text
User
 ↓
ATM
 ↓
Controlled Access
 ↓
Bank Account Data
```

### 💻 Java Example

```java
class BankAccount {

    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}
```

Here:

- `balance` → hidden using `private`
- `deposit()` → controlled modification
- `getBalance()` → controlled access

### 🧩 Main Components

- private data
- public methods
- Getters
- Setters

### ✨ Benefits

- Data hiding
- Controlled access
- Better security
- Maintainability
- Prevents unwanted modification

### 🧠 Easy Remember

Encapsulation = Data + Methods + Controlled Access

---

## 2.4 Inheritance

### 📖 What is Inheritance?

Inheritance allows one class to acquire the properties and behaviors of another class.

```text
Parent Class
     ↓
Child Class
```

### 👪 Simple Analogy

Think of a parent and child.

A child can inherit certain characteristics from the parent.

In Java:

```text
Vehicle
   ↓
Car
```

A Car can inherit common features from Vehicle.

### 💻 Java Example

```java
class Vehicle {

    void start() {
        System.out.println("Vehicle starts");
    }
}

class Car extends Vehicle {

    void drive() {
        System.out.println("Car is driving");
    }
}
```

Usage:

```java
Car car = new Car();

car.start();  // inherited
car.drive();  // own method
```

### 🔑 Keyword

`extends` is used for class inheritance.

### 🧩 Types of Inheritance

```text
Inheritance
├── Single
├── Multilevel
├── Hierarchical
└── Multiple → Not supported through classes
```

### Single Inheritance

```text
Animal
   ↓
Dog
```

### Multilevel Inheritance

```text
Animal
   ↓
Mammal
   ↓
Dog
```

### Hierarchical Inheritance

```text
       Animal
       /    \
     Dog    Cat
```

### Multiple Inheritance

Java does not support multiple inheritance through classes.

```text
Class A     Class B
    \       /
     ❌ Class C
```

However, Java supports multiple inheritance of type through interfaces.

### ✅ Advantages

- Code reusability
- Reduces duplication
- Supports method overriding
- Represents hierarchical relationships

### ❌ Disadvantages

- Creates tight relationships between parent and child
- Deep inheritance hierarchies can become difficult to maintain
- Changes in parent class can affect child classes

### 🧠 Easy Remember

Inheritance = IS-A relationship

Examples:

- Car IS-A Vehicle
- Dog IS-A Animal
- Manager IS-A Employee

---

## 2.5 Polymorphism

### 📖 What is Polymorphism?

Polymorphism means "one thing, many forms."

In Java, the same method or reference can behave differently depending on the situation.

### 🧑 Simple Analogy

Think of a person:

```text
Person
 ├── Student → studies()
 ├── Teacher → teaches()
 └── Doctor  → treats()
```

The same person can have different roles and behaviors.

### 🧩 Types of Polymorphism

```text
Polymorphism
├── Compile-Time Polymorphism
│   └── Method Overloading
│
└── Runtime Polymorphism
    └── Method Overriding
```

---

## 2.6 Method Overloading

### 📖 What is Method Overloading?

Having multiple methods with the same name but different parameters in the same class.

### 💻 Example

```java
class Calculator {

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

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

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

The method name is the same: `add()`
But the parameters are different.

### What can change?

- Number of parameters
- Type of parameters
- Order of parameters

### 📌 Important

Changing only the return type does NOT create overloading.

```java
// ❌ Invalid
int add(int a, int b)
double add(int a, int b)
```

### 🧠 Easy Remember

Overloading = Same class + Same method name + Different parameters

### When?

Usually used when the same operation needs different inputs.

---

## 2.7 Method Overriding

### 📖 What is Method Overriding?

When a child class provides its own implementation of a method already defined in the parent class.

### 💻 Example

```java
class Animal {

    void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {

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

Usage:

```java
Dog dog = new Dog();
dog.sound();
```

Output:

```text
Dog barks
```

### 📌 Important Rules

- Requires inheritance
- Same method name
- Same parameters
- Child provides new implementation
- `@Override` is recommended

### ⚡ Runtime Polymorphism

```java
Animal animal = new Dog();

animal.sound();
```

Output:

```text
Dog barks
```

The method that runs is determined at runtime based on the actual object.

### 🧠 Easy Remember

Overriding = Parent method → Child changes its behavior

### ⚖️ Overloading vs Overriding

| Method Overloading                     | Method Overriding                  |
| -------------------------------------- | ---------------------------------- |
| Compile-time polymorphism              | Runtime polymorphism               |
| Usually within the same class          | Requires parent-child relationship |
| Same method name                       | Same method signature              |
| Parameters must differ                 | Parameters must be same            |
| Inheritance not required               | Inheritance required               |
| Return type alone cannot differentiate | Compatible return type required    |

### 🧠 One-Line Memory Trick

- Overloading → Same name, different inputs
- Overriding → Same method, different implementation

---

## 2.8 Abstraction

### 📖 What is Abstraction?

Abstraction means hiding implementation details and showing only the essential features.

### 🚗 Simple Analogy

Think about driving a car.

You use:

- Steering → Turn
- Brake → Stop
- Accelerator → Speed

You don't need to know how the engine internally performs these operations.

```text
User
 ↓
Essential Features
 ↓
Hidden Implementation
```

### In Java

Abstraction is mainly achieved using:

```text
Abstraction
├── Abstract Classes
└── Interfaces
```

### ✨ Advantages

- Hides implementation details
- Reduces complexity
- Improves maintainability
- Provides clear structure
- Supports loose coupling

### 🧠 Easy Remember

Abstraction = What to do, not how it is done

---

## 2.9 Abstract Classes

### 📖 What is an Abstract Class?

A class declared with the `abstract` keyword that cannot be directly instantiated.

It can contain:

- Abstract methods
- Concrete methods
- Variables
- Constructors

### 💻 Example

```java
abstract class Animal {

    abstract void sound();

    void eat() {
        System.out.println("Animal eats");
    }
}
```

Child class:

```java
class Dog extends Animal {

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

Usage:

```java
Dog dog = new Dog();

dog.sound();
dog.eat();
```

### 🔑 Abstract Method

A method declared without implementation.

```java
abstract void sound();
```

The child class must provide the implementation.

### 📌 Important Points

- Cannot create an object directly: `// ❌ Animal a = new Animal();`
- Can have constructors
- Can have abstract and non-abstract methods
- Can have instance variables
- A class can extend only one class

### 🧠 Easy Remember

Abstract Class = Partial implementation + abstraction

---

## 2.10 Interfaces

### 📖 What is an Interface?

An interface defines a contract that implementing classes must follow.

```java
interface Payment {

    void pay();
}
```

Implementation:

```java
class UPI implements Payment {

    @Override
    public void pay() {
        System.out.println("Payment through UPI");
    }
}
```

Usage:

```java
Payment payment = new UPI();

payment.pay();
```

### 🔑 Keyword

- `interface` → creates an interface
- `implements` → implements an interface

### ✨ Important Features

- Supports abstraction
- Provides a contract
- Enables loose coupling
- A class can implement multiple interfaces
- Interface methods are commonly used to define required behavior
- Interfaces can also contain default and static methods

### Multiple Interfaces

```java
interface A {
    void methodA();
}

interface B {
    void methodB();
}

class C implements A, B {

    public void methodA() {
    }

    public void methodB() {
    }
}
```

```text
A ──┐
    ├──> C
B ──┘
```

### ⚖️ Abstract Class vs Interface

| Abstract Class                                  | Interface                                         |
| ----------------------------------------------- | ------------------------------------------------- |
| Uses abstract class                             | Uses interface                                    |
| Extended using `extends`                        | Implemented using `implements`                    |
| Can have constructors                           | Cannot have normal constructors                   |
| Can have instance variables                     | Primarily defines a contract                      |
| Can contain abstract + concrete methods         | Can contain abstract, default, and static methods |
| Class can extend only one class                 | Class can implement multiple interfaces           |
| Useful when classes share common state/behavior | Useful for defining common contracts              |

### 🧠 Easy Memory Trick

- Abstract Class → "What should be common?"
- Interface → "What must be implemented?"

---

# 3️⃣ Java Access & Modifiers

## 3.1 Access Modifiers

Access modifiers control the visibility/accessibility of classes, methods, variables, and constructors.

### 🧩 Types

```text
Access Modifiers
├── private
├── default
├── protected
└── public
```

| Modifier  | Same Class | Same Package | Subclass | Everywhere |
| --------- | ---------- | ------------ | -------- | ---------- |
| private   | ✅         | ❌           | ❌       | ❌         |
| default   | ✅         | ✅           | ❌\*     | ❌         |
| protected | ✅         | ✅           | ✅       | ❌\*       |
| public    | ✅         | ✅           | ✅       | ✅         |

> \* `protected` has additional access rules across packages through inheritance.

### private

Accessible only within the same class.

```java
class Student {
    private int age;
}
```

### Default

No modifier is specified. Accessible within the same package.

```java
class Student {
    int age;
}
```

### protected

Accessible within the same package and by subclasses.

```java
class Student {
    protected int age;
}
```

### public

Accessible from anywhere.

```java
public class Student {
    public int age;
}
```

### 🧠 Easy Remember

- private → Class
- default → Package
- protected → Package + Child
- public → Everywhere

---

## 3.2 Non-Access Modifiers

Non-access modifiers define the behavior or characteristics of classes, methods, and variables.

Common examples:

```text
Non-Access Modifiers
├── static
├── final
├── abstract
├── synchronized
├── volatile
├── transient
└── native
```

For this course, focus mainly on: **static** and **final**

---

## 3.3 static

`static` means the member belongs to the class rather than individual objects.

### Static Variable

```java
class Student {

    static String college = "ABC College";
}
```

All objects share the same `college` variable.

```java
Student.college;
```

### Static Method

```java
class Calculator {

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

Called using the class name:

```java
Calculator.add(10, 20);
```

### Static Block

```java
class Student {

    static {
        System.out.println("Static block executed");
    }
}
```

Executed when the class is loaded.

### 📌 Important Points

- Belongs to the class
- Can be accessed using the class name
- Static methods cannot directly access non-static instance members
- `main()` is static

### 🧠 Easy Remember

static → Class-level

---

## 3.4 final

`final` is used to restrict modification.

It can be used with variables, methods, and classes.

### Final Variable

Value cannot be changed after assignment.

```java
final int MAX = 100;

// MAX = 200; ❌
```

### Final Method

Cannot be overridden by a child class.

```java
class Parent {

    final void display() {
        System.out.println("Hello");
    }
}
```

### Final Class

Cannot be inherited.

```java
final class Vehicle {
}
// class Car extends Vehicle { } ❌
```

### 🧠 Easy Remember

- final variable → Cannot change
- final method → Cannot override
- final class → Cannot inherit

---

## 3.5 this

`this` refers to the current object.

### 💻 Example

```java
class Student {

    String name;

    Student(String name) {
        this.name = name;
    }
}
```

Here:

- `this.name` → instance variable
- `name` → constructor parameter

### 🔁 Common Uses

- Refer to current object's instance variable
- Call current class method
- Call another constructor using `this()`
- Pass the current object as an argument

### 💻 Example

```java
class Student {

    void display() {
        System.out.println("Student");
    }

    void show() {
        this.display();
    }
}
```

### 🧠 Easy Remember

this → Current object

---

## 3.6 super

`super` refers to the immediate parent class.

### Access Parent Variable

```java
class Parent {
    int value = 10;
}

class Child extends Parent {
    int value = 20;

    void display() {
        System.out.println(super.value);
    }
}
```

Output:

```text
10
```

### Call Parent Method

```java
class Parent {

    void display() {
        System.out.println("Parent");
    }
}

class Child extends Parent {

    void display() {
        super.display();
        System.out.println("Child");
    }
}
```

### Call Parent Constructor

```java
class Parent {

    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {

    Child() {
        super();
        System.out.println("Child Constructor");
    }
}
```

### 🔁 Common Uses

- Access parent variable
- Call parent method
- Call parent constructor

### 🧠 Easy Remember

super → Parent object/class context

---

## 🔁 Quick Revision

```text
Java Access & Modifiers
│
├── Access Modifiers
│   ├── private
│   ├── default
│   ├── protected
│   └── public
│
├── Non-Access Modifiers
│   ├── static
│   └── final
│
├── this
│   └── Current Object
│
└── super
    └── Parent Class
```

### 🧠 One-Line Memory

- Access modifiers → Who can access?
- static → Belongs to class
- final → Restricts change/inheritance/overriding
- this → Current object
- super → Parent class

# 4️⃣ Packages

## 4.1 Packages

### 📖 What is a Package?

A package is a group of related classes, interfaces, and other Java components.

### 🤔 Why Packages?

- Organize code
- Avoid naming conflicts
- Control access
- Improve project structure

### 💻 Example

```text
com.example
├── Student.java
├── Teacher.java
└── Course.java
```

### Syntax

```java
package com.example;
```

### 🧠 Easy Remember

Package = Folder for Java classes

---

## 4.2 Import

### 📖 What is import?

`import` allows you to use classes from another package without writing their fully qualified name every time.

### 💻 Example

```java
import java.util.ArrayList;

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

Without import:

```java
java.util.ArrayList<String> names =
        new java.util.ArrayList<>();
```

### 🧩 Types

```java
import java.util.ArrayList;
import java.util.*;
```

- Single class import
- Wildcard import

### 📌 Important

`java.lang` is automatically imported.

- String
- System
- Math
- Integer

can be used without explicitly importing `java.lang`.

---

## 4.3 Built-in Packages

Java provides many predefined packages.

### 📦 Common Packages

| Package     | Purpose                 | Examples                    |
| ----------- | ----------------------- | --------------------------- |
| `java.lang` | Core Java               | String, System, Math        |
| `java.util` | Collections & utilities | ArrayList, HashMap, Scanner |
| `java.io`   | Input/Output            | File, FileReader            |
| `java.time` | Date & Time             | LocalDate, LocalDateTime    |
| `java.sql`  | Database connectivity   | Connection, Statement       |

Example:

```java
import java.util.ArrayList;
import java.time.LocalDate;
```

---

## 4.4 User-Defined Packages

### 📖 What is a User-Defined Package?

A package created by the developer to organize their own classes.

### 💻 Example Structure

```text
src
└── com
    └── example
        ├── model
        │   └── Student.java
        │
        └── service
            └── StudentService.java
```

**Student.java**

```java
package com.example.model;

public class Student {
    public void display() {
        System.out.println("Student");
    }
}
```

**Using the Class**

```java
import com.example.model.Student;

public class Main {

    public static void main(String[] args) {
        Student student = new Student();
        student.display();
    }
}
```

### Package Naming Convention

Usually written in lowercase:

```text
com.company.project
org.example.application
```

### 🧠 Easy Remember

- `package` → Create/organize
- `import` → Use another package's class
- Built-in → Java provides it
- User-defined → Developer creates it

---

# 5️⃣ Exception Handling

## 5.1 Exceptions

### 📖 What is an Exception?

An exception is an unwanted event that occurs during program execution and can interrupt the normal flow of the program.

```java
int result = 10 / 0;
```

This causes:

```text
ArithmeticException
```

### 🤔 Why Exception Handling?

- Prevent abnormal program termination
- Handle runtime problems
- Maintain normal program flow
- Provide meaningful error messages

### 🌳 Exception Hierarchy

```text
Throwable
├── Error
└── Exception
    ├── RuntimeException
    └── Other Exceptions
```

---

## 5.2 Checked Exceptions

Checked exceptions are checked by the compiler.

The programmer must handle them using try-catch or declare them using `throws`.

Examples:

- IOException
- SQLException
- FileNotFoundException

```java
import java.io.FileReader;
import java.io.IOException;

void readFile() throws IOException {
    FileReader file = new FileReader("data.txt");
}
```

### 🧠 Easy Remember

Checked → Compiler checks

---

## 5.3 Unchecked Exceptions

Unchecked exceptions occur mainly during runtime and are not checked by the compiler.

They are subclasses of `RuntimeException`.

Examples:

- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- NumberFormatException

```java
int x = 10 / 0;
```

### 🧠 Easy Remember

Unchecked → Runtime checks

---

## 5.4 try

The `try` block contains code that may cause an exception.

```java
try {
    int result = 10 / 0;
}
```

A try block must be followed by `catch`, `finally`, or both.

---

## 5.5 catch

`catch` is used to handle an exception thrown from the try block.

```java
try {
    int result = 10 / 0;
}
catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
```

### Multiple Catch Blocks

```java
try {
    // risky code
}
catch (ArithmeticException e) {
    // handle arithmetic error
}
catch (Exception e) {
    // handle general exception
}
```

More specific exceptions should generally come before broader exceptions.

---

## 5.6 finally

The `finally` block is used for code that should execute whether an exception occurs or not in normal execution.

```java
try {
    System.out.println("Try");
}
catch (Exception e) {
    System.out.println("Catch");
}
finally {
    System.out.println("Finally");
}
```

Commonly used for:

- Closing resources
- Cleanup operations

### 🧠 Easy Remember

- try → Risky code
- catch → Handle error
- finally → Cleanup

---

## 5.7 throw

`throw` is used to explicitly throw an exception.

```java
if (age < 18) {
    throw new IllegalArgumentException("Age must be 18 or above");
}
```

### 🧠 Easy Remember

throw → Actually throws an exception

---

## 5.8 throws

`throws` is used in a method declaration to declare that a method may throw one or more exceptions.

```java
void readFile() throws IOException {
    // file operation
}
```

The caller must handle or further declare the exception.

### ⚖️ throw vs throws

| throw                               | throws                          |
| ----------------------------------- | ------------------------------- |
| Used to actually throw an exception | Declares possible exceptions    |
| Used inside method/body             | Used in method declaration      |
| Throws one exception at a time      | Can declare multiple exceptions |

```java
throw new Exception();

void test() throws IOException, SQLException {
}
```

---

## 5.9 Custom Exceptions

### 📖 What is a Custom Exception?

An exception created by the developer for a specific application requirement.

### 💻 Example

```java
class InsufficientBalanceException extends Exception {

    public InsufficientBalanceException(String message) {
        super(message);
    }
}
```

Using it:

```java
void withdraw(double amount)
        throws InsufficientBalanceException {

    if (amount > 5000) {
        throw new InsufficientBalanceException(
            "Insufficient balance"
        );
    }
}
```

### 🧩 Types

Custom exceptions can be created as:

```text
Custom Exception
├── Checked
│   └── extends Exception
│
└── Unchecked
    └── extends RuntimeException
```

### 🔄 Complete Exception Handling Flow

```text
Risky Code
    ↓
   try
    ↓
Exception occurs?
   ├── No → Continue
   │
   └── Yes
        ↓
      catch
        ↓
    Handle Exception
        ↓
     finally
        ↓
      Continue
```

## 🔁 Quick Revision

- Exception → Problem during execution
- Checked → Compiler checks
- Unchecked → Runtime checks
- try → Code that may fail
- catch → Handle exception
- finally → Cleanup
- throw → Explicitly throw
- throws → Declare possible exception
- Custom Exception → Application-specific exception

---

# 6️⃣ Java Collections

## 6.1 Collection Framework

### 📖 What is Collection Framework?

The Java Collection Framework (JCF) is a set of interfaces and classes used to store and manipulate groups of objects.

### 🌳 Main Structure

```text
                    Collection
                       │
          ┌────────────┼────────────┐
          │            │            │
         List          Set         Queue
          │            │
     ┌────┴────┐    ┌──┴─────┐
 ArrayList  LinkedList HashSet
```

`Map` is part of the Collection Framework but does not extend `Collection`.

```text
Map
├── HashMap
├── LinkedHashMap
└── TreeMap
```

---

## 6.2 List

### 📖 What is List?

List is an ordered collection that:

- Allows duplicate elements
- Maintains insertion order
- Supports index-based access

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

### 🔧 Important Methods

```text
add()
add(index, element)
get(index)
set(index, element)
remove(index)
contains()
size()
isEmpty()
clear()
```

---

## 6.3 ArrayList

`ArrayList` is a resizable array implementation of `List`.

```java
ArrayList<String> names = new ArrayList<>();

names.add("Ravi");
names.add("Kumar");
names.add("Ravi");
```

### 🔧 Important Methods

```java
names.add("John");
names.get(0);
names.set(0, "Alex");
names.remove(1);
names.contains("Ravi");
names.size();
```

### 📌 Key Points

- Maintains insertion order
- Allows duplicates
- Fast random/index access
- Dynamic size

### 🧠 Easy Remember

ArrayList → Dynamic Array

---

## 6.4 LinkedList

`LinkedList` stores elements using a linked-node structure.

```java
LinkedList<String> names = new LinkedList<>();

names.add("Ravi");
names.add("Kumar");
```

### 🔧 Important Methods

```text
add()
addFirst()
addLast()
get()
getFirst()
getLast()
remove()
removeFirst()
removeLast()
contains()
size()
```

### 📌 Key Points

- Maintains insertion order
- Allows duplicates
- Efficient insertion/removal at appropriate positions
- Slower random/index access compared with ArrayList

### 🧠 Easy Remember

LinkedList → Linked nodes

---

## 6.5 Set

### 📖 What is Set?

Set is a collection that does not allow duplicate elements.

```java
Set<String> names = new HashSet<>();

names.add("Ravi");
names.add("Ravi");
names.add("Kumar");
```

Result:

```text
Ravi
Kumar
```

### 🔧 Important Methods

```text
add()
remove()
contains()
size()
isEmpty()
clear()
```

---

## 6.6 HashSet

`HashSet` is a common implementation of `Set`.

```java
HashSet<Integer> numbers = new HashSet<>();

numbers.add(10);
numbers.add(20);
numbers.add(10);
```

### 📌 Key Points

- No duplicates
- Does not guarantee insertion order
- Allows one null element
- Uses hashing internally
- Fast lookup in typical cases

### 🧠 Easy Remember

HashSet → Unique elements

---

## 6.7 Map

### 📖 What is Map?

Map stores data as key-value pairs.

```text
Key → Value
```

Example:

```text
101 → Ravi
102 → Kumar
103 → Arun
```

```java
Map<Integer, String> students = new HashMap<>();

students.put(101, "Ravi");
students.put(102, "Kumar");
```

### 📌 Important Points

- Keys must be unique
- Values can be duplicated
- Each key maps to one value

### 🔧 Important Methods

```text
put()
get()
remove()
containsKey()
containsValue()
size()
isEmpty()
clear()
keySet()
values()
entrySet()
```

---

## 6.8 HashMap

`HashMap` is a common implementation of `Map`.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(101, "Ravi");
students.put(102, "Kumar");

System.out.println(students.get(101));
```

Output:

```text
Ravi
```

### 📌 Key Points

- Stores key-value pairs
- Keys are unique
- Does not guarantee insertion order
- Allows one null key
- Allows multiple null values
- Uses hashing internally

### 🧠 Easy Remember

HashMap → Key + Value

---

## 6.9 Iterator

### 📖 What is Iterator?

Iterator is used to traverse elements of a collection one by one.

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

names.add("Ravi");
names.add("Kumar");

Iterator<String> iterator = names.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
```

### 🔧 Important Methods

```text
hasNext()
next()
remove()
```

### 🧠 Easy Remember

Iterator → Move through collection

---

## 6.10 Generics

### 📖 What are Generics?

Generics provide type safety by specifying what type of data a collection can store.

Without Generics:

```java
List names = new ArrayList();
```

With Generics:

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

Now only String values can be added.

```java
names.add("Ravi");     // ✅
names.add(100);        // ❌
```

### Common Generic Types

```text
List<String>
List<Integer>
Set<String>
Map<Integer, String>
```

### Generic Class Example

```java
class Box<T> {

    T value;

    void set(T value) {
        this.value = value;
    }

    T get() {
        return value;
    }
}
```

Usage:

```java
Box<String> box = new Box<>();
box.set("Hello");
```

### 🧠 Easy Remember

Generics → Type Safety

---

## 🧭 Quick Collection Selection

```text
Need ordered + duplicates?
        ↓
      List
        ↓
   ArrayList / LinkedList


Need unique elements?
        ↓
       Set
        ↓
     HashSet


Need key-value pairs?
        ↓
       Map
        ↓
     HashMap
```

## 🔁 Quick Memory

- List → Ordered + Duplicates
- Set → Unique
- Map → Key + Value
- ArrayList → Dynamic Array
- LinkedList → Linked Nodes
- HashSet → Unique + Hashing
- HashMap → Key-Value + Hashing
- Iterator → Traverse
- Generics → Type Safety

---

# 7️⃣ Java 8+ Features

## 7.1 Lambda Expressions

### 📖 What is a Lambda Expression?

A lambda expression is a short way to write the implementation of a functional interface method.

### Syntax

```java
(parameters) -> expression
```

### 💻 Example

```java
(a, b) -> a + b
```

Instead of:

```java
interface Calculator {
    int add(int a, int b);
}

Calculator c = (a, b) -> a + b;
```

### 🧠 Easy Remember

Lambda → Shorter way to write behavior

---

## 7.2 Functional Interfaces

### 📖 What is a Functional Interface?

An interface that contains exactly one abstract method.

```java
@FunctionalInterface
interface Calculator {
    int add(int a, int b);
}
```

Common built-in functional interfaces:

```text
Predicate<T>  → true / false
Function<T,R> → input → output
Consumer<T>   → consumes input
Supplier<T>   → supplies output
```

### 🧠 Easy Remember

Functional Interface → One abstract method

---

## 7.3 Method References

### 📖 What is a Method Reference?

A method reference is a shorter form of a lambda expression when an existing method can be directly used.

### Syntax

```java
ClassName::methodName
```

### 💻 Example

```java
names.forEach(System.out::println);
```

Equivalent lambda:

```java
names.forEach(name -> System.out.println(name));
```

### 🧩 Types

```text
ClassName::staticMethod
object::instanceMethod
ClassName::instanceMethod
ClassName::new
```

### 🧠 Easy Remember

Method Reference → Reuse an existing method

---

## 7.4 Stream API

### 📖 What is Stream API?

Stream API is used to process collections of data in a clean and functional style.

```text
Collection
    ↓
  Stream
    ↓
Filter → Transform → Collect
```

### 💻 Example

```java
List<Integer> numbers = List.of(1, 2, 3, 4, 5);

List<Integer> result = numbers.stream()
        .filter(n -> n % 2 == 0)
        .toList();
```

Result:

```text
[2, 4]
```

### 🔧 Common Operations

**Intermediate:**

```text
filter()
map()
sorted()
distinct()
limit()
```

**Terminal:**

```text
forEach()
collect()
toList()
count()
reduce()
```

### 🧠 Easy Remember

Stream → Process data

---

## 7.5 Optional

### 📖 What is Optional?

Optional is a container that may or may not contain a value.

It helps reduce problems related to null.

```java
Optional<String> name = Optional.of("Ravi");
```

### 🔧 Common Methods

```text
of()
ofNullable()
isPresent()
ifPresent()
orElse()
orElseGet()
orElseThrow()
```

### 💻 Example

```java
String name = Optional
        .ofNullable(value)
        .orElse("Unknown");
```

### 🧠 Easy Remember

Optional → Value may or may not exist

---

## 7.6 forEach

`forEach()` is used to perform an action for every element.

```java
List<String> names = List.of("Ravi", "Kumar", "Arun");

names.forEach(name -> System.out.println(name));
```

Using method reference:

```java
names.forEach(System.out::println);
```

### 🧠 Easy Remember

forEach → Do something for every element

---

# 8️⃣ Java I/O Basics

## 8.1 File Handling

### 📖 What is File Handling?

File handling is used to create, read, write, and manage files.

Common class: `File`

Example:

```java
File file = new File("data.txt");

System.out.println(file.exists());
```

### 🔧 Common Operations

- Create
- Read
- Write
- Delete
- Check existence
- Get file information

---

## 8.2 Input Streams

### 📖 What is an Input Stream?

An input stream is used to read data into a Java program.

```text
File / Source
     ↓
Input Stream
     ↓
Java Program
```

Common classes:

```text
InputStream
FileInputStream
BufferedInputStream
```

Example:

```java
FileInputStream input =
        new FileInputStream("data.txt");
```

### 🧠 Easy Remember

Input → Data comes INTO the program

---

## 8.3 Output Streams

### 📖 What is an Output Stream?

An output stream is used to write data from a Java program to a destination.

```text
Java Program
     ↓
Output Stream
     ↓
File / Destination
```

Common classes:

```text
OutputStream
FileOutputStream
BufferedOutputStream
```

Example:

```java
FileOutputStream output =
        new FileOutputStream("data.txt");
```

### 🧠 Easy Remember

Output → Data goes OUT of the program

---

# 9️⃣ Important Java Concepts

## 9.1 String

### 📖 What is String?

String represents a sequence of characters.

```java
String name = "Ravi";
```

### 📌 Important Characteristics

- Immutable
- Object of String class
- Supports many built-in methods

### 🔧 Common Methods

```text
length()
charAt()
substring()
equals()
equalsIgnoreCase()
contains()
startsWith()
endsWith()
toUpperCase()
toLowerCase()
trim()
replace()
split()
```

### 💻 Example

```java
String name = "Ravi";

System.out.println(name.length());
System.out.println(name.toUpperCase());
```

### 🧠 Easy Remember

String → Immutable text

---

## 9.2 StringBuilder

### 📖 What is StringBuilder?

StringBuilder is a mutable sequence of characters used when frequent string modifications are required.

```java
StringBuilder sb = new StringBuilder("Hello");

sb.append(" Java");

System.out.println(sb);
```

### 🔧 Common Methods

```text
append()
insert()
delete()
replace()
reverse()
toString()
```

### 📌 Key Point

Mutable + Faster for frequent modifications + Not thread-safe

---

## 9.3 StringBuffer

### 📖 What is StringBuffer?

StringBuffer is also a mutable sequence of characters, but its methods are synchronized.

```java
StringBuffer sb = new StringBuffer("Hello");

sb.append(" Java");
```

### 📌 Key Point

Mutable + Thread-safe + Generally slower than StringBuilder

### ⚖️ String vs StringBuilder vs StringBuffer

|                          | String                     | StringBuilder | StringBuffer              |
| ------------------------ | -------------------------- | ------------- | ------------------------- |
| Mutable                  | ❌                         | ✅            | ✅                        |
| Thread-safe              | ✅ Immutable               | ❌            | ✅                        |
| Modification performance | Lower for repeated changes | Faster        | Slower than StringBuilder |

---

## 9.4 Wrapper Classes

### 📖 What are Wrapper Classes?

Wrapper classes provide object representations of primitive data types.

```text
Primitive → Wrapper
```

| Primitive | Wrapper   |
| --------- | --------- |
| byte      | Byte      |
| short     | Short     |
| int       | Integer   |
| long      | Long      |
| float     | Float     |
| double    | Double    |
| char      | Character |
| boolean   | Boolean   |

### Autoboxing

Primitive → Object

```java
int x = 10;
Integer y = x;
```

### Unboxing

Object → Primitive

```java
Integer x = 10;
int y = x;
```

### 🤔 Why?

Collections work with objects:

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

---

## 9.5 Enum

### 📖 What is Enum?

`enum` is used to define a fixed set of constants.

```java
enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY
}
```

Usage:

```java
Day today = Day.MONDAY;
```

### Common Usage

- Days
- Months
- Status
- Roles
- Categories

Example:

```java
enum Status {
    PENDING,
    APPROVED,
    REJECTED
}
```

### 🧠 Easy Remember

Enum → Fixed set of values

---

## 9.6 equals()

### 📖 What is equals()?

`equals()` is used to compare objects based on their logical/content equality when the class provides an appropriate implementation.

```java
String a = new String("Java");
String b = new String("Java");

System.out.println(a.equals(b));
```

Output:

```text
true
```

### ⚖️ == vs equals()

```text
==        → Reference identity
equals()  → Logical/content equality
```

For String:

```java
a == b          // compares references
a.equals(b)     // compares content
```

---

## 9.7 hashCode()

### 📖 What is hashCode()?

`hashCode()` returns an integer hash value representing an object, mainly used by hash-based collections such as HashMap and HashSet.

```java
int hash = object.hashCode();
```

### 📌 Important Contract

If:

```text
a.equals(b) == true
```

then:

```text
a.hashCode() == b.hashCode()
```

The reverse is not necessarily true.

### 🧠 Easy Remember

- equals() → Are they logically equal?
- hashCode() → Which hash bucket/value should represent them?

---

## 9.8 toString()

### 📖 What is toString()?

`toString()` returns a string representation of an object.

```java
class Student {

    String name;

    @Override
    public String toString() {
        return "Student{name='" + name + "'}";
    }
}
```

Usage:

```java
Student s = new Student();
s.name = "Ravi";

System.out.println(s);
```

Output:

```text
Student{name='Ravi'}
```

### 🧠 Easy Remember

toString() → Object → Readable String

---

## 🔁 Quick Revision

```text
Java 8+
│
├── Lambda Expressions
├── Functional Interfaces
├── Method References
├── Stream API
├── Optional
└── forEach

Java I/O
│
├── File Handling
├── Input Streams
└── Output Streams

Important Concepts
│
├── String
├── StringBuilder
├── StringBuffer
├── Wrapper Classes
├── Enum
├── equals()
├── hashCode()
└── toString()
```

### 🧠 One-Line Memory

- Lambda → Short behavior
- Functional Interface → One abstract method
- Method Reference → Existing method
- Stream → Process data
- Optional → May contain a value
- String → Immutable text
- StringBuilder → Mutable, fast
- StringBuffer → Mutable, synchronized
- Wrapper → Primitive as object
- Enum → Fixed constants
- equals() → Logical equality
- hashCode() → Hash value
- toString() → String representation
