Java Notes(Part 3)
๐ 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 โ CollegeSo 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 guaranteedUsed in:
HashMap
HashSet
Hashtable๐งฌ 4. getClass() โ Runtime Information
System.out.println(s1.getClass().getName());Output:
StudentFrom your notes:
Returns runtime class of object๐งช 5. instanceof Operator
System.out.println(s1 instanceof Object); // trueExample:
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 Threadswait()โ pause threadnotify()โ wake one threadnotifyAll()โ 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 mistakesExample 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 objectSo:
Direction.NORTHis 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 finalSo:
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 conflictSolved 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 APriority:
Class > InterfaceSo 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 APIExamples:
Runnable
Comparable
Predicate๐ท๏ธ Marker Interfaces
From your notes (page 3):
Marker interface โ empty interfaceExamples:
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 changedExample:
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







