Sitemap

Java Notes(Part 3)

12 min readMar 28, 2026

--

๐Ÿ” Immutable Classes in Java โ€” Explained with Real Code

If youโ€™ve been learning Java, youโ€™ve probably heard this line:

โ€œString is immutable.โ€

But what does immutability actually mean?
And more importantly โ€” how do you design your own immutable classes correctly?

Letโ€™s break it down step by step with a real example ๐Ÿ‘‡

๐Ÿš€ What is Immutability?

Immutability means:

Once an object is created, its state cannot be changed.

Example:

String s = "Java";
s = "Python";

๐Ÿ‘‰ Here, the original "Java" string is not modified.
๐Ÿ‘‰ A new object "Python" is created.

โš ๏ธ Real Problem: Not Truly Immutable

Consider this code:

College college = new College("IIT G", "Assam");
Student s1 = new Student(28, "Aditya", college);
System.out.println(s1.getCollege().name); // IIT Gs1.getCollege().name = "IIT B";System.out.println(s1.getCollege().name); // IIT B โŒ

At first glance, Student looks immutable:

  • final class โœ”
  • private final fields โœ”
  • No setters โœ”

But stillโ€ฆ the data changed ๐Ÿ˜จ

๐Ÿ’ฅ Why This Happens

The issue is reference sharing.

Student โ†’ holds reference โ†’ College

So when you do:

s1.getCollege().name = "IIT B";

๐Ÿ‘‰ You are modifying the same College object inside Student.

This is called:

โŒ Shallow Copy Problem

๐Ÿง  Solution: Defensive Copying

To make your class truly immutable, you must protect internal objects.

โœ… Step 1: Copy in Constructor

this.college = new College(college.name, college.address);

โœ… Step 2: Return Copy in Getter

public College getCollege() {
return new College(this.college.name, this.college.address);
}

โœ… Final Correct Immutable Class

final class Student {
    private final int age;
private final String name;
private final College college;
Student(int age, String name, College college) {
this.age = age;
this.name = name;
this.college = new College(college.name, college.address); // defensive copy
}
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public College getCollege() {
return new College(this.college.name, this.college.address); // defensive copy
}
}

๐ŸŽฏ Now What Happens?

s1.getCollege().name = "IIT B";

๐Ÿ‘‰ This modifies only the copy, not the original.

System.out.println(s1.getCollege().name); // IIT G โœ…

โœ” Your object is now truly immutable

๐Ÿ”’ Why Immutability is Important

1. Security

Sensitive data cannot be modified accidentally.

2. Thread Safety

Immutable objects are automatically thread-safe.

3. Caching (String Pool)

Java can reuse objects efficiently.

4. Performance

No need for synchronization โ†’ faster programs.

โš–๏ธ Mutable vs Immutable

Mutable โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” -Immutable

Can change โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” -Cannot change

Not thread-safe โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Thread-safe

Example: ArrayList โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Example: String

๐Ÿงต Immutability & Threads

Mutable objects can cause:

Race Condition โŒ

Immutable objects:

Safe for multiple threads โœ…

๐Ÿ”ฅ Rules to Create Immutable Class

1. Make class final
2. Make fields private and final
3. No setter methods
4. Initialize via constructor
5. Use defensive copying for mutable objects

๐Ÿง  Interview Questions

โ“ Why is String immutable?

๐Ÿ‘‰ Security + caching + thread safety

โ“ Is final enough for immutability?

๐Ÿ‘‰ โŒ No
Mutable objects inside can still break it

โ“ What is defensive copying?

๐Ÿ‘‰ Returning a new object instead of original reference

โ“ Shallow vs Deep Copy?

Shallow โ†’ same reference โŒ
Deep โ†’ new object copy โœ…

โœ๏ธ Final Thoughts

Immutability is not just about using final.

Itโ€™s about completely protecting the internal state of an object.

โœ” Use final
โœ” Avoid setters
โœ” Always use defensive copying

๐Ÿง  Java Object Class โ€” The Most Important Class You Ignore

Every Java developer uses objects dailyโ€ฆ but very few truly understand the Object class.

Hereโ€™s the truth:

Every class in Java implicitly extends the Object class.

Even if you donโ€™t write it:

class Student {
}

Internally it becomes:

class Student extends Object {
}

๐Ÿ‘‰ This is also clearly shown in your notes where every class ultimately links to Object as the root (page 1).

๐Ÿ”‘ Why Object Class is Important

The Object class provides common behavior to all Java objects:

toString()
equals()
hashCode()
getClass()
clone()
wait(), notify(), notifyAll()
finalize()

๐Ÿ” 1. toString() โ€” Object Representation

Default behavior:

Student s1 = new Student();
System.out.println(s1);

Output:

Student@1a2b3c

๐Ÿ‘‰ From your notes (page 2):

ClassName@HexCode

โœ… Override toString()

@Override
public String toString() {
return name + " , " + age;
}

Now:

System.out.println(s1);

Output:

Aditya , 28

โš–๏ธ 2. equals() โ€” Comparing Objects

Default:

Compares memory reference โŒ

From your notes:

s1 == s2 โ†’ reference comparison

โœ… Custom equals()

@Override
public boolean equals(Object obj) {
    if(this == obj) return true;    if(obj == null) return false;    if(obj.getClass() != this.getClass()) return false;    Student s = (Student) obj;    return (this.name == s.name && this.age == s.age);
}

๐Ÿ‘‰ Now compares actual values

3. hashCode() โ€” Hashing Mechanism

If two objects are equal โ†’ hashCode must be equal

โœ… Implementation

@Override
public int hashCode() {
return Objects.hash(name, age);
}

โš ๏ธ Important Rule

equals() true โ†’ hashCode must be same
BUT reverse is not guaranteed

Used in:

HashMap
HashSet
Hashtable

๐Ÿงฌ 4. getClass() โ€” Runtime Information

System.out.println(s1.getClass().getName());

Output:

Student

From your notes:

Returns runtime class of object

๐Ÿงช 5. instanceof Operator

System.out.println(s1 instanceof Object); // true

Example:

Animal a = new Animal();
Animal d = new Dog();
System.out.println(a instanceof Dog);     // false
System.out.println(d instanceof Animal); // true

๐Ÿ‘‰ Used to check object type and inheritance

๐Ÿงฌ 6. clone() โ€” Copying Objects

From your notes (page 4):

clone() โ†’ creates copy (shallow copy by default)

โœ… Example

Student s3 = (Student) s1.clone();

โš ๏ธ Important Points

  • Must implement Cloneable
  • Otherwise โ†’ CloneNotSupportedException
class Student implements Cloneable {
}

๐Ÿง  Shallow vs Deep Copy

From your notes:

Shallow Copy โ†’ same reference โŒ
Deep Copy โ†’ new object copy โœ…

๐Ÿงต 7. wait(), notify(), notifyAll()

From your notes (page 1):

Used in Threads
  • wait() โ†’ pause thread
  • notify() โ†’ wake one thread
  • notifyAll() โ†’ wake all threads

Used in synchronization

๐Ÿ—‘๏ธ 8. finalize() โ€” Garbage Collection

From your notes:

finalize() โ†’ called before object destroyed

โš ๏ธ Deprecated now โ†’ do not use in modern Java

๐Ÿง  Internal Concept (Important)

From your diagrams:

Object โ†’ parent of all classes
Provides common behavior โ†’ inheritance + polymorphism

๐Ÿ”ฅ Interview Questions

โ“ Why Object class is root class?

๐Ÿ‘‰ To provide common methods to all objects

โ“ Difference between == and equals()

== โ†’ reference comparison
equals() โ†’ value comparison

โ“ Why override hashCode() with equals()?

๐Ÿ‘‰ Required for hashing collections

โ“ clone() default type?

๐Ÿ‘‰ Shallow copy

โ“ Can all objects be cloned?

From your notes:

โŒ No (Database, Threads should not be cloned)

โœ๏ธ Final Thoughts

The Object class is the foundation of Java OOP.

Understanding it deeply means:

โœ” Better design
โœ” Better debugging
โœ” Strong interview preparation

๐Ÿš€ Java Enums โ€” From Constants to Powerful Classes

When you start learning Java, you often write constants like this:

class PaymentStatus {
public static final String SUCCESS = "Success";
public static final String FAILED = "Failed";
public static final String PENDING = "Pending";
}

Looks fineโ€ฆ right? โŒ
Actually, this approach has serious problems.

โŒ Problems with Constants Approach

1. No Type Safety
2. Poor Readability
3. No Grouping of related values
4. Easy to make mistakes

Example bug:

String status = "random"; // still allowed โŒ

๐Ÿ‘‰ This is exactly why Enums were introduced.

โœ… What is Enum in Java?

Enum = a special class that represents a fixed set of constants

Example:

enum PaymentStatus {
SUCCESS,
FAILED,
PENDING;
}

Usage:

PaymentStatus status = PaymentStatus.FAILED;
System.out.println(status);

๐Ÿ” Why Use Enums?

โœ” Type Safety

PaymentStatus status = PaymentStatus.SUCCESS;

โŒ Invalid values not allowed

โœ” Better Readability

if(status == PaymentStatus.SUCCESS)

โœ” Logical Grouping

All related constants are grouped together.

๐Ÿง  Internal Working (Very Important)

From your notes:

Enum is internally a class extending java.lang.Enum (page 1)

Each constant = static final object

So:

Direction.NORTH

is actually:

public static final Direction NORTH = new Direction();

๐Ÿงช Enum Example with Methods

enum Direction {
NORTH(0),
SOUTH(180),
EAST(90),
WEST(270);
    private int degree;    Direction(int degree) {
this.degree = degree;
}
public int getDegree() {
return this.degree;
}
}

Usage:

Direction d = Direction.SOUTH;
System.out.println(d.getDegree()); // 180

๐Ÿ”ฅ Enum with Abstract Methods (Advanced)

From your notes (page 3), each enum constant can have its own behavior.

enum Direction {
    NORTH {
public void move() {
System.out.println("Move up (Y + 1)");
}
},
SOUTH {
public void move() {
System.out.println("Move down (Y - 1)");
}
};
public abstract void move();
}

๐Ÿ‘‰ Each constant behaves like a separate class

๐Ÿ” Built-in Enum Methods

From your notes (page 4):

1. values()

Direction[] dirs = Direction.values();

๐Ÿ‘‰ Returns all constants

2. valueOf()

Direction d = Direction.valueOf("EAST");

๐Ÿ‘‰ Converts string โ†’ enum

3. name()

System.out.println(d.name());

๐Ÿ‘‰ Returns constant name

4. ordinal()

System.out.println(d.ordinal());

๐Ÿ‘‰ Position index (0,1,2โ€ฆ)

๐Ÿ”„ Enum in Switch

switch(status) {
case SUCCESS:
System.out.println("Success");
break;
case FAILED:
System.out.println("Failed");
break;
}

โš–๏ธ Enum vs Constants

Constants โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Enum

Get Deepaksinghโ€™s stories inย yourย inbox

Join Medium for free to get updates fromย thisย writer.

No type safety โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€”Type safe

Simple variables โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Full class

Error-prone โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Safe

No behavior โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” -Can have methods

๐Ÿง  Key Concept

From your notes:

Enum = class
โ†’ has state (variables)
โ†’ has behavior (methods)

๐ŸŽฏ Real Use Cases

Payment Status โ†’ SUCCESS, FAILED
Days โ†’ MONDAY, TUESDAY
User Roles โ†’ ADMIN, USER
Directions โ†’ NORTH, SOUTH
Logs โ†’ INFO, ERROR, DEBUG

๐Ÿ”ฅ Interview Questions

โ“ Is enum a class?

๐Ÿ‘‰ Yes, it extends java.lang.Enum

โ“ Can enum have constructor?

๐Ÿ‘‰ Yes (always private)

โ“ Can enum have methods?

๐Ÿ‘‰ Yes

โ“ Can enum implement interface?

๐Ÿ‘‰ Yes

โ“ Why enum is better than constants?

๐Ÿ‘‰ Type safety + readability + structure

โœ๏ธ Final Thoughts

Enums are not just constants.

They are powerful classes with fixed instances.

If youโ€™re building backend systems or preparing for interviews:

โœ” Always prefer enums over constants
โœ” Use behavior inside enums
โœ” Treat enums like real classes

๐Ÿš€ Java Interfaces โ€” The Real Power Behind Abstraction

When you start learning Java OOP, you hear this word a lot:

Interface = contract

But what does that really mean?

Letโ€™s understand deeply with real code and concepts ๐Ÿ‘‡

๐Ÿง  What is an Interface?

An interface defines what an object can do, not how it does it

From your notes:

Interface โ†’ blueprint of behaviour (contract)

(page 1)

โœ… Basic Example

interface Payment {
void pay();
}

Implementation:

class CreditCard implements Payment {
public void pay() {
System.out.println("Paying via credit card");
}
}

Usage:

Payment p = new DebitCard();
p.pay();

๐Ÿ‘‰ This is runtime polymorphism

๐Ÿ”ฅ Why Use Interfaces?

1. Abstraction
2. Loose coupling
3. Multiple inheritance
4. Flexible design

๐Ÿ”‘ Key Rule

Interface = what to do
Class = how to do

๐Ÿงฉ Variables in Interface

From your code:

interface MathConstant {
double PI_VALUE = 3.14;
}

๐Ÿ‘‰ Internally:

public static final

So:

System.out.println(MathConstant.PI_VALUE);

โœ” No object needed

๐Ÿ”— Multiple Inheritance (Very Important)

Java does not support multiple inheritance with classes โŒ
But supports with interfaces โœ…

interface A { void fun(); }
interface B { void fun2(); }
class C implements A, B {
public void fun() {}
public void fun2() {}
}

๐Ÿ”„ Interface Inheritance

interface Animal {
void eat();
}
interface Dog extends Animal {
void bark();
}

๐Ÿ‘‰ Child interface inherits parent interface

โšก Java 8+ Features (Game Changer)

From your notes (page 2):

Default methods
Static methods
Private methods (Java 9)

โœ… Default Method

interface Vehicle {
default void drive() {
System.out.println("Vehicle is driving");
accelerate();
}
    private void accelerate() {
System.out.println("Accelerating");
}
}

๐Ÿ‘‰ Allows method implementation inside interface

โœ… Static Method

Vehicle.brake();

๐Ÿ‘‰ Called using interface name

๐Ÿ’ฅ Diamond Problem (Important)

From your notes:

Diamond Problem โ†’ multiple inheritance conflict

Solved in Java by forcing override

class D implements B, C {
public void fun() {
System.out.println("D");
}
}

๐Ÿ‘‰ You must resolve ambiguity

๐Ÿง  Method Resolution Rule

From your example:

class C extends B implements A

Priority:

Class > Interface

So class method is chosen first.

โš–๏ธ Interface vs Abstract Class

Interface โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Abstract ClassContract (can-do) โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” -IS-A relationship

No constructors โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€”Has constructors

Multiple inheritance โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€”Single inheritance

Methods public โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” โ€” Any access modifier

โšก Functional Interface (Java 8)

interface A {
void fun();
}

๐Ÿ‘‰ Only one abstract method

Used in:

Lambda expressions
Streams API

Examples:

Runnable
Comparable
Predicate

๐Ÿท๏ธ Marker Interfaces

From your notes (page 3):

Marker interface โ†’ empty interface

Examples:

Cloneable
Serializable
RandomAccess

๐Ÿ‘‰ Used to mark a class

Example:

class Student implements Cloneable {
}

๐Ÿง  Key Concept

From your notes:

Interface = Roles / Capabilities
Runnable, Payable, Walkable

โœ” Focus on behavior, not hierarchy

๐ŸŽฏ Real World Examples

Payment system โ†’ CreditCard, UPI, NetBanking
Vehicle โ†’ Car, Bike
User roles โ†’ Admin, User

๐Ÿ”ฅ Interview Questions

โ“ Can interface have variables?

๐Ÿ‘‰ Yes โ†’ static + final

โ“ Can interface have methods with body?

๐Ÿ‘‰ Yes (default, static, private)

โ“ Can interface extend another interface?

๐Ÿ‘‰ Yes

โ“ Multiple inheritance possible?

๐Ÿ‘‰ Yes (using interfaces)

โ“ What is functional interface?

๐Ÿ‘‰ Interface with single abstract method

โ“ Marker interface example?

๐Ÿ‘‰ Cloneable, Serializable

โœ๏ธ Final Thoughts

Interfaces are not just syntax โ€” they are design tools

They help you:

โœ” Build flexible systems
โœ” Achieve loose coupling
โœ” Write scalable backend code

๐Ÿ”ฅ Java Strings โ€” Deep Dive (Memory, Pool, Immutability Explained)

Strings look simpleโ€ฆ but they are one of the most powerful and tricky topics in Java.

If you understand this properly, you unlock:

โœ” Memory optimization
โœ” Interview questions
โœ” Backend performance

Letโ€™s break it down step by step ๐Ÿ‘‡

๐Ÿง  What is a String in Java?

From your notes:

String โ†’ sequence of characters
Class โ†’ java.lang.String

(page 1)

Example:

String s = "Hello";

๐Ÿ” Important Property

String is IMMUTABLE

Once created โ†’ cannot be changed

Example:

String s = "Hello";
s = "World";

๐Ÿ‘‰ New object created, old one unchanged

๐Ÿ’ก Why String is Immutable?

From your notes:

Used in โ†’ passwords, URLs, hashing

(page 1)

Reasons:

โœ” Security
โœ” Thread safety
โœ” String pool optimization
โœ” Hashcode caching

๐Ÿง  String Memory (Very Important)

Java uses 3 memory areas:

Stack โ†’ reference
Heap โ†’ objects
String Pool โ†’ special area inside heap

๐Ÿ”ฅ String Literal vs new String()

โœ… Literal (Stored in String Pool)

String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true

๐Ÿ‘‰ Both refer to same object in pool

From your notes (page 2):

Compile-time constants โ†’ go to string pool

โŒ Using new (Stored in Heap)

String s3 = new String("Aditya");
String s4 = new String("Aditya");
System.out.println(s3 == s4); // false

๐Ÿ‘‰ Different objects in heap

โš–๏ธ == vs equals()

s1 == s2   โ†’ reference comparison
s1.equals(s2) โ†’ value comparison

โšก Compile-Time vs Runtime Strings

โœ… Compile Time

String s1 = "Ja" + "va";
String s2 = "Java";
System.out.println(s1 == s2); // true

๐Ÿ‘‰ Optimized at compile time โ†’ goes to pool

โŒ Runtime

String s3 = "Hello";
String s4 = s3 + " World";
String s5 = "Hello World";
System.out.println(s4 == s5); // false

๐Ÿ‘‰ Created at runtime โ†’ goes to heap

๐Ÿง  Golden Rule (From Notes)

Compile-time โ†’ String Pool
Runtime โ†’ Heap

(page 2)

๐Ÿ” String Reassignment

String s = "Hello";
s = "World";

๐Ÿ‘‰ Now:

"Hello" โ†’ still exists
"World" โ†’ new object

๐Ÿ”ฅ String Pool Internals

From your diagram (page 2 & 3):

Pool stores unique strings only
Multiple references โ†’ same object

โšก intern() Method

String s1 = new String("Hello");
String s2 = s1.intern();
System.out.println(s1 == s2); // false

๐Ÿ‘‰ intern() returns reference from string pool

โš ๏ธ Problem with Immutability

Your code:

String s = "";
for(int i=0; i<5; i++) {
s += i;
}

Creates:

"" โ†’ "0" โ†’ "01" โ†’ "012" โ†’ "0123" โ†’ "01234"

๐Ÿ‘‰ Multiple objects created โŒ (inefficient)

๐Ÿš€ Solution: StringBuilder

StringBuilder sb = new StringBuilder();
for(int i=0; i<5; i++) {
sb.append(i);
}

โœ” Faster
โœ” No extra objects

โš–๏ธ String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBufferMutableโŒ Noโœ” Yesโœ” YesThread-safeโœ” YesโŒ Noโœ” YesPerformanceSlowFastMedium

๐Ÿง  Internal Structure (Advanced)

From your notes (page 4 & 5):

String internally uses:
byte[] value
coder (Latin1 / UTF-16)
hash caching

๐Ÿ‘‰ Java optimizes memory using:

โœ” byte[] instead of char[]
โœ” encoding (Latin1 / UTF-16)
โœ” cached hashCode

๐Ÿ”ฅ String Optimization

From your notes:

String Pool
byte[] instead of char[]
Hashcode caching

๐ŸŽฏ Interview Questions

โ“ Why String is immutable?

๐Ÿ‘‰ Security + caching + thread safety

โ“ Difference between == and equals()

๐Ÿ‘‰ Reference vs value comparison

โ“ String pool vs heap?

๐Ÿ‘‰ Pool โ†’ reuse, Heap โ†’ new objects

โ“ What is intern()?

๐Ÿ‘‰ Moves string to pool / returns pool reference

โ“ Why StringBuilder faster?

๐Ÿ‘‰ Mutable โ†’ no new object creation

โœ๏ธ Final Thoughts

Strings are not just text โ€” they are optimized objects managed by JVM

If you understand:

โœ” String pool
โœ” Immutability
โœ” Memory behavior

--

--