Skip to content

Class

🔷 What is a Class in Java?

A class in Java is a blueprint or template used to create objects. It defines the state (fields/attributes) and behavior (methods/functions) of objects.

🔑 In short: A class is like a design, and an object is the real thing built from that design.


🧱 Fundamental Components of a Java Class

A class typically contains:

  1. Fields (Variables) – store data/state
  2. Methods – define behavior
  3. Constructors – initialize objects
  4. Access Modifiers – control visibility
  5. Objects – instances of a class

📘 Syntax of a Class

class ClassName {
    // Fields (variables)
    dataType fieldName;

    // Constructor
    ClassName() {
        // initialization code
    }

    // Methods
    returnType methodName(parameters) {
        // method body
    }
}

📦 Example: A Basic Java Class

public class Student {

    // Fields (attributes)
    String name;
    int age;

    // Constructor
    Student(String n, int a) {
        name = n;
        age = a;
    }

    // Method
    void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

🧪 How to Use the Class

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Alice", 22);  // Creating object
        s1.displayInfo();                       // Calling method
    }
}

🔍 Explanation of the Components

1️⃣ Fields / Attributes

These are variables that hold data for the object.

String name;
int age;

2️⃣ Methods

These are functions defined inside a class that perform actions.

void displayInfo() {
    System.out.println(name + " " + age);
}

3️⃣ Constructor

A special method used to initialize objects. It has the same name as the class and no return type.

Student(String n, int a) {
    name = n;
    age = a;
}

4️⃣ Objects

An object is an instance of a class — like a real "thing" created from the blueprint.

Student s1 = new Student("Alice", 22);

🔐 Access Modifiers

Used to define visibility:

Modifier Accessible Within Other Class Subclass Other Package
public
private
protected ✅ (only in subclass)
(default) ✅ (same pkg)

🧠 Why Classes Are Important

  • Enable Object-Oriented Programming
  • Allow modularity, reusability, and data encapsulation
  • Are essential for abstraction and real-world modeling

🧩 Real-Life Analogy

Think of a class as a blueprint of a car.

  • It defines the car’s properties (color, model, engine).
  • It defines behaviors (drive, stop, honk).
  • You can then create many cars (objects) from this one blueprint.

✅ Summary

Concept Description
Class Blueprint for creating objects
Object Instance of a class
Fields Store object state
Methods Define object behavior
Constructor Initializes object
Access Modifiers Control visibility

objects

🔷 What is an Object in Java?

An object is a real-world entity or an instance of a class.

💡 A class is like a blueprint or template, and an object is the actual item created using that blueprint.

🧠 Real-Life Analogy:

Think of a class as a blueprint of a car. You can create many actual cars (objects) using that blueprint.


🧱 Basic Definition

In Java:

  • A class defines fields (data) and methods (functions).
  • An object is created from the class using the new keyword.
  • Each object has its own copy of data and can call methods.

🧪 Example

🔹 Class Definition:

public class Student {
    String name;
    int age;

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

🔹 Creating Objects (In main() method):

public class Main {
    public static void main(String[] args) {
        // Creating object
        Student s1 = new Student();
        s1.name = "Alice";
        s1.age = 22;
        s1.display();  // Method call on object

        Student s2 = new Student();
        s2.name = "Bob";
        s2.age = 24;
        s2.display();
    }
}

🔄 Creating an Object: Syntax

ClassName objectName = new ClassName();

Example:

Student s1 = new Student();

📌 Explanation:

  • Student → class name
  • s1 → object (reference variable)
  • new → keyword to create object
  • Student() → constructor call

🎯 Characteristics of an Object

Feature Description
Identity Unique reference in memory
State Values of its fields (like name, age)
Behavior Actions it can perform (via methods like display())

🔍 Important Points

  • Objects consume memory during runtime.
  • You can create multiple objects from one class.
  • Each object has its own state (field values).

📘 Behind the Scenes

When you write:

Student s1 = new Student();

Java does:

  1. Allocates memory for the object.
  2. Calls the Student() constructor.
  3. Returns the memory address, stored in reference variable s1.

✅ Summary

Term Meaning
Class Blueprint/template for objects
Object Instance of a class
Fields Data members (like name, age)
Methods Functions that define behavior
new Keyword used to create an object

🧠 Example in Simple English

If Dog is a class:

  • Dog d1 = new Dog();d1 is an object of class Dog.
  • d1 can have properties like color, breed and behaviors like bark().

Methods.

Understanding methods will help you write reusable, organized, and modular code. They’re essential for object-oriented programming.

🔷 What is a Method in Java?

A method is a block of code that performs a specific task. It is used to define behavior for a class.

✅ Methods help you write code once and reuse it whenever needed.


🧠 Why Use Methods?

  • Avoid code duplication (write once, use many times)
  • Organize logic into smaller, manageable pieces
  • Improve readability, modularity, and reusability

📘 Syntax of a Method

returnType methodName(parameter1, parameter2, ...) {
    // method body
    // optional return statement
}

🔹 Example: Simple Method

public class Calculator {

    // Method without return value
    void greet() {
        System.out.println("Welcome to the Calculator!");
    }

    // Method with parameters and return value
    int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();

        calc.greet();                       // Calling method
        int result = calc.add(10, 20);      // Calling method with parameters
        System.out.println("Sum = " + result);
    }
}

🔎 Parts of a Method

Part Description
Return Type Data type returned by the method (e.g., int, void)
Method Name Name used to call the method
Parameters Input values (optional)
Method Body Code that defines what the method does
Return Statement Used if return type is not void

✅ Types of Methods in Java

1️⃣ Predefined Methods

  • Built-in methods provided by Java.
  • Examples: System.out.println(), Math.max()

2️⃣ User-defined Methods

  • Methods created by the programmer.
  • Example: int add(int a, int b)

🔁 Method Overloading (Same name, different parameters)

Java allows multiple methods with the same name but different parameter lists.

class Printer {
    void print(int a) {
        System.out.println(a);
    }

    void print(String s) {
        System.out.println(s);
    }
}

🔸 This is called method overloading.


📌 Key Rules for Methods

  1. Method must be inside a class
  2. Use return statement to return a value (if return type is not void)
  3. Method names should be verbs, written in camelCase
  4. You call a method using: objectName.methodName(arguments);

🎯 Benefits of Using Methods

Benefit Description
Reusability Call the same method multiple times
Modularity Organize code into small pieces
Debugging ease Isolate bugs to individual methods
Clarity Improves code readability

🧠 Summary

Term Meaning
Method Block of code that performs a task
Return type Type of value the method returns
Parameters Input values sent to the method
Overloading Same method name, different parameters
void Used when method doesn't return anything

✅ Final Quick Example:

public class Hello {

    // Method that returns a message
    String sayHello(String name) {
        return "Hello, " + name;
    }

    public static void main(String[] args) {
        Hello h = new Hello();
        System.out.println(h.sayHello("John"));
    }
}

Method Overloading

🔷 What is Method Overloading in Java?

Method Overloading is when two or more methods in the same class have the same name, but different parameters (either by number, type, or order).

✅ It allows a class to perform similar operations in different ways depending on input.


📘 Real-Life Example:

Think of a print() method:

  • print(int a) → prints an integer
  • print(String s) → prints a string

You’re using the same name, but the function behaves based on parameter type — that’s overloading!


🧪 Syntax & Example

public class Calculator {

    // Method 1: adds two integers
    int add(int a, int b) {
        return a + b;
    }

    // Method 2: adds three integers
    int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method 3: adds two doubles
    double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();

        System.out.println(calc.add(2, 3));         // calls method 1
        System.out.println(calc.add(2, 3, 4));      // calls method 2
        System.out.println(calc.add(2.5, 3.5));     // calls method 3
    }
}

🔑 Rules of Method Overloading

  1. Method name must be the same
  2. Parameter list must be different

  3. Different number of parameters

  4. Different type of parameters
  5. Different order of parameters
  6. Return type can be same or different, but return type alone is NOT enough to distinguish methods.

❌ Invalid Overloading Example (Only different return type)

int show() { return 1; }
double show() { return 1.5; }  // ❌ Compile-time error

Java doesn’t allow this because it can’t decide which method to call just by the return type.


🎯 Why Use Method Overloading?

Advantage Description
Clean Code No need to create different method names
Flexibility Method works with different data types
Readability Logical grouping of similar tasks
Reusability Code can be reused with different parameters

🧠 Another Example: Display Method

class Display {

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

    void show(int age) {
        System.out.println("Age: " + age);
    }

    void show(String name, int age) {
        System.out.println(name + " is " + age + " years old.");
    }

    void show(int age, String name) {
        System.out.println("Reverse order: " + name + " - " + age);
    }
}

✅ This works because the parameter type and order are different.


✅ Summary Table

Form of Overloading Example
Different number of args add(int, int) vs add(int, int, int)
Different types of args add(int, int) vs add(double, double)
Different order of types show(String, int) vs show(int, String)

🔁 Constructor Overloading

Overloading also works with constructors:

class Student {
    String name;
    int age;

    Student(String n) {
        name = n;
    }

    Student(String n, int a) {
        name = n;
        age = a;
    }
}

💬 Interview Tip

If asked:

"Can you overload a method based only on return type?"

Answer: ❌ No. Return type alone is not enough to distinguish overloaded methods.


Constructors

🔷 What is a Constructor in Java?

A constructor is a special method used to initialize objects in Java. It is automatically called when an object of a class is created.

✅ A constructor sets initial values for object attributes (fields).


🧠 Real-Life Analogy:

When you buy a phone, it comes with default settings — ringtone, brightness, etc. That’s like a constructor setting initial values when the phone (object) is made.


📘 Basic Syntax

class ClassName {
    // Constructor
    ClassName() {
        // initialization code
    }
}

⚠️ Notice: A constructor has the same name as the class and no return type, not even void.


🔹 Example

public class Student {
    String name;
    int age;

    // Constructor
    Student(String n, int a) {
        name = n;
        age = a;
    }

    void display() {
        System.out.println(name + " is " + age + " years old.");
    }

    public static void main(String[] args) {
        Student s1 = new Student("Alice", 21);  // constructor is called
        s1.display();
    }
}

🔑 Characteristics of Constructors

Feature Description
Name Same as class name
Return type None (no void, no int, etc.)
Called Automatically when object is created
Overloadable ✅ Yes (multiple constructors with different parameters)

✅ Types of Constructors in Java

1️⃣ Default Constructor

  • Provided by Java if you don’t define any constructor
  • Takes no parameters
class Car {
    Car() {
        System.out.println("Car object created.");
    }
}

2️⃣ No-argument Constructor

  • Explicitly written by the programmer with no parameters
class Book {
    Book() {
        System.out.println("Book created.");
    }
}

3️⃣ Parameterized Constructor

  • Takes parameters to initialize fields
class Employee {
    String name;
    Employee(String n) {
        name = n;
    }
}

🔁 Constructor Overloading

Just like methods, constructors can be overloaded (same name, different parameter lists):

class Person {
    Person() {
        System.out.println("Default constructor");
    }

    Person(String name) {
        System.out.println("Name: " + name);
    }

    Person(String name, int age) {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

🔄 Constructor vs Method: Key Differences

Feature Constructor Method
Name Same as class name Any valid name
Return Type No return type Must have return type (can be void)
Called When Object is created Called explicitly
Purpose Initialize object Define behavior or action

🎯 Use of this Keyword in Constructor

Used to refer to the current object’s fields.

class Laptop {
    String brand;

    Laptop(String brand) {
        this.brand = brand;  // distinguishes field from parameter
    }
}

✅ Summary

Constructor Type Description
Default Constructor Automatically created by Java if none
No-arg Constructor Constructor with no parameters
Parameterized Constructor with arguments
Overloaded Multiple constructors with different params

Recursion

🔷 What is Recursion?

Recursion is a technique where a method calls itself to solve a problem by breaking it down into smaller, simpler sub-problems.

🧠 Definition: A method that solves a problem by calling itself with a simpler input.


Why use recursion?

  • It simplifies code for problems that have a recursive structure, like mathematical series, tree traversals, factorials, Fibonacci numbers, etc.
  • Makes some complex problems easier to understand and solve.

Key idea:

Every recursive method must have:

  1. Base Case (Stopping condition) — When to stop the recursion.
  2. Recursive Case — The method calls itself with a smaller or simpler input.

Example: Factorial of a number (n!)

Factorial of n is the product of all positive integers up to n. Mathematically:

  • factorial(n) = n * factorial(n-1)
  • Base case: factorial(0) = 1

Java Code:

public class RecursionExample {

    // Recursive method to calculate factorial
    public static int factorial(int n) {
        if (n == 0) {              // Base case
            return 1;
        } else {
            return n * factorial(n - 1);   // Recursive call
        }
    }

    public static void main(String[] args) {
        int number = 5;
        int fact = factorial(number);
        System.out.println("Factorial of " + number + " is " + fact);
    }
}

How it works for factorial(5):

factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1 * factorial(0)
= 5 * 4 * 3 * 2 * 1 * 1
= 120

Important Points About Recursion:

Point Explanation
Base Case Essential to stop recursion, else leads to infinite calls.
Recursive Case Method calls itself with smaller input.
Stack Memory Each call is stored on call stack until base case reached.
Risk of Stack Overflow If base case is missing or incorrect, program crashes.
Can often be replaced by loops Iterative loops sometimes used instead of recursion.

Another example: Fibonacci series

public static int fibonacci(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Advantages of Recursion

  • Code can be more readable and elegant.
  • Solves problems naturally defined recursively (trees, graphs, divide and conquer).

Disadvantages of Recursion

  • Uses more memory (call stack).
  • May be slower due to overhead of multiple function calls.
  • Needs careful base case design to avoid infinite recursion.

Summary

Term Explanation
Recursion A method calling itself to solve smaller subproblems.
Base Case The stopping condition for recursion.
Recursive Case The part where method calls itself with simpler input.
Stack Overflow Error caused if recursion never stops (no base case).

Garbage Collection

🔷 What is Garbage Collection in Java?

Garbage Collection (GC) is the process by which Java automatically reclaims memory by destroying objects that are no longer needed or reachable by the program.

✅ It helps prevent memory leaks and optimizes memory usage without manual intervention.


Why Garbage Collection?

  • In Java, objects are created on the heap memory.
  • When objects are no longer referenced (used), they become garbage.
  • Manually freeing memory (like in C/C++) is not required; Java does it automatically.
  • Garbage Collection frees up heap memory to make it available for new objects.

How Does Garbage Collection Work?

  1. Object Creation: When you create objects using new, they are stored in heap memory.
  2. Reachability: Java tracks which objects are reachable via references.
  3. Unreachable Objects: Objects without any active references are considered eligible for garbage collection.
  4. GC Process: JVM’s garbage collector periodically runs to:

  5. Identify unreachable objects.

  6. Free the memory occupied by them.

Example:

public class GarbageExample {
    public static void main(String[] args) {
        GarbageExample obj1 = new GarbageExample();
        GarbageExample obj2 = new GarbageExample();

        obj1 = null; // obj1 object is now eligible for GC
        obj2 = null; // obj2 object is now eligible for GC

        System.gc(); // Suggest JVM to run Garbage Collector
    }
}

Note: System.gc() requests GC but JVM decides when to run it.


Key Concepts in Java Garbage Collection

Concept Explanation
Heap Memory Memory area where objects are allocated.
Reachable Object Object that can be accessed through references.
Unreachable Object Object that is no longer referenced and eligible for GC.
Finalization finalize() method allows an object to clean up before GC removes it (deprecated in newer Java versions).

Types of References

  • Strong Reference: Normal references; objects are not eligible for GC.
  • Soft Reference: GC clears these only if memory is low.
  • Weak Reference: GC clears these more aggressively.
  • Phantom Reference: Used for more complex cleanup.

How Garbage Collector Works Internally?

  • Uses algorithms like Mark-and-Sweep, Generational GC.
  • JVM divides heap into:

  • Young Generation (new objects)

  • Old Generation (long-lived objects)
  • GC is more frequent in Young Gen and less in Old Gen (because objects that survive many GCs are likely to stay longer).

Benefits of Garbage Collection

  • Automatic memory management reduces programmer burden.
  • Helps prevent memory leaks and dangling pointers.
  • Improves application stability.

Limitations

  • GC can cause pause times (stop-the-world events), affecting performance.
  • You cannot predict exactly when GC will run.
  • Overuse of objects may lead to frequent GC and overhead.

Summary Table

Term Description
Garbage Collection Automatic process to free unused memory
Reachable Object Object accessible by references
Unreachable Object Object no longer referenced, eligible for GC
System.gc() Suggests JVM to run garbage collector
Heap Memory area where objects live

Access Controls

🔷 What are Access Controls in Java?

Access control in Java is a mechanism to restrict access to classes, methods, variables, and constructors. It helps protect data and hide implementation details from unauthorized parts of a program.

🔐 Access control determines which other classes or packages can access a particular member or class.


Types of Access Modifiers in Java

There are four main access modifiers in Java:

Access Modifier Where Accessible Keyword Example
public Anywhere (any class, any package) public
protected Same package + subclasses (even in other packages) protected
default (no modifier) Only within the same package No keyword (default access)
private Only within the same class private

Explanation of Each Modifier

1️⃣ public

  • The member or class is accessible from anywhere.
  • Use for APIs or things you want visible to all parts of your program.

2️⃣ protected

  • Accessible within the same package.
  • Accessible in subclasses even if they are in different packages.
  • Commonly used for methods or variables intended to be inherited.

3️⃣ Default (Package-Private)

  • If you don’t specify any modifier, it’s accessible only within the same package.
  • Good for internal package use but hidden outside.

4️⃣ private

  • Accessible only within the same class.
  • Not visible to any other class (even subclasses).
  • Used to hide sensitive data and implementation details.

Example Code:

package com.example;

public class AccessExample {

    public int publicVar = 10;       // Accessible everywhere
    protected int protectedVar = 20; // Accessible in package & subclasses
    int defaultVar = 30;             // Accessible only in same package
    private int privateVar = 40;     // Accessible only inside this class

    public void show() {
        System.out.println("publicVar: " + publicVar);
        System.out.println("protectedVar: " + protectedVar);
        System.out.println("defaultVar: " + defaultVar);
        System.out.println("privateVar: " + privateVar);
    }
}

How Access Modifiers Apply to:

Java Element Access Modifiers Allowed
Class public, default (package-private) only
Method/Variable public, protected, default, private
Constructor Same as methods/variables

⚠️ Note: Top-level classes cannot be private or protected.


Why Use Access Control?

Reason Explanation
Encapsulation Hide internal data & implementation
Security Protect sensitive data from misuse
Modularity Restrict access to only necessary parts
Maintainability Easier to modify code without breaking others

Summary Table

Modifier Same Class Same Package Subclass (same package) Subclass (different package) World (anywhere)
public Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes No
default Yes Yes Yes No No
private Yes No No No No

static methods & fixed methods (usually the term is final methods)

🔷 Static Methods in Java

What is a static method?

  • A static method belongs to the class itself, not to any particular object (instance).
  • You can call a static method without creating an object of the class.
  • Static methods cannot access instance variables or methods directly because they don't belong to any object.

Syntax:

class MyClass {
    static void staticMethod() {
        System.out.println("This is a static method.");
    }
}

How to call:

MyClass.staticMethod();  // Call static method using class name

Key points about static methods:

Feature Explanation
Called by Class name (no object needed)
Can access Only static variables and other static methods
Cannot access Instance variables or methods
Used for Utility or helper methods, shared methods
Example Math.sqrt(), Integer.parseInt()

🔷 Final Methods (possibly what you mean by "fixed methods")

What is a final method?

  • A final method cannot be overridden by subclasses.
  • Used when you want to prevent a method from being changed by inheritance.

Syntax:

class Parent {
    final void show() {
        System.out.println("Final method - cannot be overridden.");
    }
}

Why use final methods?

  • To ensure method behavior remains consistent.
  • To increase security and reliability.
  • To optimize method calls (JVM can inline final methods).

Summary Table:

Feature Static Method Final Method
Belongs to Class Instance (object)
Override possible Yes (can override instance methods) No (cannot be overridden)
Called by Class name Object of the class
Can access Only static members Instance and static members
Purpose Utility methods, class-level actions Prevent method overriding

Example combining both:

class Example {
    static void staticMethod() {
        System.out.println("Static method called.");
    }

    final void finalMethod() {
        System.out.println("Final method called.");
    }
}

class SubExample extends Example {
    // Cannot override finalMethod() here (compiler error)
}

Inner Classes

🔷 What are Inner Classes in Java?

An inner class is a class defined within another class. Inner classes are used to logically group classes that are only used in one place, increase encapsulation, and make code more readable and maintainable.


Why use Inner Classes?

  • To group related classes together.
  • To access members (even private) of the outer class easily.
  • To create event handlers or helper classes inside another class.
  • Helps with encapsulation by hiding the inner class from outside.

Types of Inner Classes in Java

Type Description
Non-static Inner Class (aka Instance Inner Class) Associated with an instance of the outer class. Can access instance members of outer class.
Static Nested Class Static class defined inside another class. Cannot access instance members of outer class directly.
Local Inner Class Defined inside a method or block; scope limited to that method/block.
Anonymous Inner Class No name; used for creating one-time use subclasses, often for event handling or callbacks.

1️⃣ Non-static Inner Class Example

class Outer {
    private int outerData = 10;

    class Inner {
        void display() {
            System.out.println("Outer data is " + outerData);
        }
    }
}

public class TestInner {
    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();  // Creating inner class object
        inner.display();
    }
}
  • Inner class can access private members of outer class.
  • Need an instance of outer class to create inner class.

2️⃣ Static Nested Class Example

class Outer {
    static int data = 30;

    static class StaticNested {
        void display() {
            System.out.println("Data is " + data);
        }
    }
}

public class TestStaticNested {
    public static void main(String[] args) {
        Outer.StaticNested nested = new Outer.StaticNested();
        nested.display();
    }
}
  • Does not have access to instance members of outer class.
  • Can be instantiated without an outer class object.

3️⃣ Local Inner Class Example

class Outer {
    void method() {
        class LocalInner {
            void msg() {
                System.out.println("Hello from local inner class");
            }
        }

        LocalInner li = new LocalInner();
        li.msg();
    }
}

public class TestLocalInner {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.method();
    }
}
  • Defined inside method; scope limited to method.
  • Useful for helper classes used in single method.

4️⃣ Anonymous Inner Class Example

abstract class Person {
    abstract void eat();
}

public class TestAnonymous {
    public static void main(String[] args) {
        Person p = new Person() {  // Anonymous inner class
            void eat() {
                System.out.println("Eating...");
            }
        };

        p.eat();
    }
}
  • No class name.
  • Used to provide implementation on the spot, commonly in event handling or threading.

Summary Table

Inner Class Type Can Access Outer Class Members Created Using Outer Class Instance? Typical Use Case
Non-static Inner Class Yes (even private) Yes When inner class needs outer instance
Static Nested Class Only static members No Grouping static helper classes
Local Inner Class Yes N/A (inside method) Helper class inside method
Anonymous Inner Class Yes N/A One-time use, often event handling

String class

🔷 What is the String Class in Java?

  • String is a built-in Java class used to represent a sequence of characters (text).
  • Strings in Java are immutable, meaning once created, their contents cannot be changed.
  • It is part of the java.lang package and used extensively in Java programs.

Key Characteristics of String

Feature Description
Immutable Once created, a String object cannot be changed.
Stored in String Pool Java optimizes memory by storing strings in a special area called the String Pool.
Object String is an object, not a primitive data type.
Rich API Provides many methods to manipulate text.

Creating Strings

  1. Using String Literals
String s1 = "Hello";
  • Stored in the String Pool.
  • If another String with the same literal is created, it reuses the existing one.

  • Using new keyword

String s2 = new String("Hello");
  • Creates a new String object in the heap, not necessarily in the String Pool.

Important String Methods

Method Description Example
length() Returns the length of the string "Hello".length() → 5
charAt(int index) Returns character at specified index "Hello".charAt(1)'e'
substring(int start, int end) Returns substring between indices "Hello".substring(1,4)"ell"
equals(Object obj) Compares two strings for content equality "Hi".equals("Hi")true
equalsIgnoreCase(String s) Compares ignoring case "hi".equalsIgnoreCase("HI")true
concat(String s) Concatenates two strings "Hi".concat(" there")"Hi there"
toUpperCase() Converts string to uppercase "hello".toUpperCase()"HELLO"
toLowerCase() Converts string to lowercase "HELLO".toLowerCase()"hello"
trim() Removes leading and trailing spaces " hello ".trim()"hello"
replace(char old, char new) Replaces characters "hello".replace('l','p')"heppo"

Why is String Immutable?

  • Security: Strings are used in many places like network connections, file paths — immutability ensures safety.
  • String Pooling: Immutability allows sharing of String objects to save memory.
  • Thread Safety: Immutable objects are naturally thread-safe.
  • Performance: Hashcodes can be cached to speed up lookups in collections like HashMap.

String Pool Explanation

  • The String Pool is a special memory area inside the JVM heap.
  • When you create a string literal, JVM checks the pool:

  • If string exists, it returns the reference.

  • If not, adds the new string to the pool.

Example:

String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);  // true (both refer to same object in pool)

But

String s3 = new String("Java");
System.out.println(s1 == s3);  // false (different objects)

Summary

Point Explanation
String is an object Not a primitive
Immutable Cannot be changed once created
Stored in String Pool Reused for memory efficiency
Created via literals or new Literals go to pool, new creates new object
Has many useful methods For manipulation and comparison