0% found this document useful (0 votes)
3 views29 pages

Java Static Keyword p2

The document discusses the static keyword in Java, focusing on static methods, their syntax, access rules, and differences from instance methods. It explains the concept of method hiding versus overriding, the significance of the main() method being static, and provides examples of utility classes that contain only static methods. Key access rules for static methods are outlined, emphasizing what they can and cannot access.

Uploaded by

Rakesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views29 pages

Java Static Keyword p2

The document discusses the static keyword in Java, focusing on static methods, their syntax, access rules, and differences from instance methods. It explains the concept of method hiding versus overriding, the significance of the main() method being static, and provides examples of utility classes that contain only static methods. Key access rules for static methods are outlined, emphasizing what they can and cannot access.

Uploaded by

Rakesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

☕ Java Programming

Static Keyword in Java


Static Methods • Access Rules • Static vs Instance • Method Hiding • Utility Classes

📌 Part-1 Ka Quick Recap


Part-1 mein humne seekha tha Static Variable aur Static Block ke baare mein. Ab Part-2 mein hum Static Methods
detail mein samjhenge — kaise banate hain, kaise call karte hain, aur Access Rules kya hain.

✅ Part-1 mein covered: 🔶 Part-2 mein cover hoga:


• Static Variable — shared property • Static Methods — syntax & use cases
• Memory Model — Class Area vs Heap • Access Rules — kya access, kya nahi
• Static Block — ek baar execute • Method Hiding vs Overriding
• Execution Order • Utility Classes — real-world pattern

🔷 Static Method — Object Ke Bina Kaam Karne Wala Method


Normal methods tab call hote hain jab hum pehle ek object banate hain — phir us object se method call karte hain.
Lekin Static Method directly CLASS se call hota hai — koi bhi object banane ki zaroorat NAHI hoti!

Static Method = Class ka kaam karne wala banda — jo seedha class se milta hai. Jaise government ka helpline
number — tum ghar baithe call karte ho, koi officer tumhare paas aata nahi. Number (class) se seedha connect!

2.1 — Syntax aur Basic Example


// Static Method — Basic Syntax aur Call
// Static Method — Syntax
class ClassName {
static returnType methodName(parameters) {
// sirf static variables aur static methods access ho sakte hain
}
}

// Call karne ka tarika:


[Link](arguments); // ✅ Best Practice — class naam se
// [Link](args); // ⚠️ Works but gives warning — avoid karo

//
────────────────────────────────────────────────────
─────────────
// Real Example
class MathHelper {

// static method — object ki zaroorat nahi


static int square(int n) {
return n * n;
}

static double circleArea(double radius) {


return 3.14159 * radius * radius;
}

static int max(int a, int b) {


return a > b ? a : b;
}

static boolean isEven(int n) {


return n % 2 == 0;
}
}

public class Main {


public static void main(String[] args) {

// ✅ Object banaye bina seedha call!


[Link]([Link](7)); // 49
[Link]([Link](5.0)); // 78.53...
[Link]([Link](15, 28)); // 28
[Link]([Link](42)); // true

// ❌ Yeh karne ki zaroorat nahi — but works (with IDE warning):


// MathHelper obj = new MathHelper();
// [Link](7); // Works but bad practice!
}
}

// Output:
// 49
// 78.53975
// 28
// true
2.2 — main() Method Bhi Static Kyun Hai? — Interview Favorite!
Yeh ek bahut common interview question hai: 'Java ka main() method static kyun hota hai?' Answer simple aur
logical hai:

🎯 Answer JVM (Java Virtual Machine) program run karne ke liye main() method call karta hai.
Lekin JVM ne abhi tak koi bhi object nahi banaya — program toh abhi shuru hi ho raha
hai!

Agar main() static nahi hota, toh JVM ko pehle ek object banana padta — lekin
object banane ke liye pehle class load karni hoti — yeh chicken-egg problem ho jaata!

Solution: main() static rakho — JVM directly class se call kare bina object ke.
Isliye: public static void main(String[] args) — yeh signature hamesha same rehta hai.

// main() static kyun hai — JVM ka flow


// main() static hai — isliye JVM object banaye bina call kar sakta hai
public class MyProgram {

// JVM yeh call karta hai: [Link](args)


// Koi object nahi banata — directly class se!
public static void main(String[] args) {
[Link]("Program shuru ho gaya!");

// Yahan se hum objects bana sakte hain


MyProgram obj = new MyProgram();
[Link]("Rakesh"); // Instance method call
}

// Instance method — object chahiye


void greet(String name) {
[Link]("Namaste, " + name + "!");
}
}

// JVM internally: [Link](new String[]{}) call karta hai


// — koi MyProgram object nahi banta pehle!
🔷 Static Method Access Rules — Kya Access Kar Sakta Hai, Kya Nahi?
Yeh Part-2 ka sabse important section hai — aur interview mein sabse zyada poochha jaata hai! Static methods ke
andar kya access ho sakta hai — yeh samajhna bahut zaroori hai.

Static Method ek aisa banda hai jo class ke bahar khada hai — ghar (object) ke andar ki cheezein seedha nahi
pakad sakta. Sirf woh cheezein le sakta hai jo class ki entrance par rakhi hain (static members)!

3.1 — The Golden Rules — Hamesha Yaad Rakhna


✅ Static Method KAR SAKTA HAI ❌ Static Method NAHI KAR SAKTA
✅ Static variables access karna ❌ Instance variables directly access karna
✅ Static methods call karna ❌ Instance methods directly call karna
✅ Local variables banake use karna ❌ this keyword use karna
✅ Parameters receive karna ❌ super keyword use karna
✅ Objects banake unke methods call karna ❌ Non-static inner class access karna

3.2 — Access Rules — Code se Prove Karte Hain


// Access Rules — Static vs Instance method ke andar kya kya hota hai
// Access Rules — Sabkuch ek jagah dekhte hain
class AccessDemo {

// Static members
static int staticVar = 100;
static String staticName = "Static World";

// Instance members
int instanceVar = 200;
String instanceName = "Instance World";

// ══════════════════════════════════════════
// STATIC METHOD — Access Rules
// ══════════════════════════════════════════
static void staticMethod() {
// ✅ Static variables — seedha access
[Link]("staticVar: " + staticVar);
[Link]("staticName: " + staticName);
staticVar = 999; // ✅ Modify bhi kar sakte
// ✅ Static methods — seedha call
anotherStaticMethod();

// ✅ Local variables — bilkul theek


int localX = 50;
[Link]("Local: " + localX);

// ✅ Object banake instance members access KARO


AccessDemo obj = new AccessDemo();
[Link]("Instance via object: " + [Link]);
[Link]();

// ❌ this keyword — COMPILE ERROR!


// [Link]([Link]); // ERROR: 'this' cannot be used in static

// ❌ Instance variable directly — COMPILE ERROR!


// [Link](instanceVar); // ERROR: Non-static field 'instanceVar'

// ❌ Instance method directly — COMPILE ERROR!


// instanceMethod(); // ERROR: Non-static method 'instanceMethod()'
}

static void anotherStaticMethod() {


[Link]("Another static method called! ✅");
}

// ══════════════════════════════════════════
// INSTANCE METHOD — Access Rules
// ══════════════════════════════════════════
void instanceMethod() {
// ✅ Static members — seedha access
[Link]("Static from instance: " + staticVar);
staticMethod(); // ✅ Static method call kar sakte hain
[Link](); // ✅ Yeh bhi sahi hai

// ✅ Instance members — bilkul theek


[Link]("Instance: " + instanceVar);
[Link]("[Link]: " + [Link]); // ✅ this available hai
}
}

public class Main {


public static void main(String[] args) {
// Static method — object ki zaroorat nahi
[Link]();

[Link]("---");

// Instance method — object chahiye


AccessDemo obj = new AccessDemo();
[Link]();
}
}

3.3 — this Keyword Static mein Kyun NAHI? — Deep Explanation


Yeh concept interviews mein bahut poochha jaata hai. Samjho deeply:

🧠 Reason 'this' keyword ka matlab hai: 'CURRENT OBJECT ka reference'.

Static method tab bhi call ho sakta hai jab koi bhi object exist nahi karta —
sirf class exist karti hai. Toh 'current object' kaun hai? KOI NAHI!

Java compiler bolta hai: 'Main this nahi de sakta kyunki is waqt koi object hi nahi hai.'

Isliye static context mein this aur super dono BANNED hain — yeh dono
object-level concepts hain, class-level nahi.

// Why 'this' is banned in static context


// 'this' kyun nahi — Visual Proof
class Counter {
static int count = 0;
String name;

Counter(String name) { [Link] = name; count++; }

static void showCount() {


// Yahan JVM ke paas koi bhi object nahi ho sakta:
[Link]("Total counters: " + count); // ✅
// this kaun hai? Object 1? Object 2? Object 3?
// Pata hi nahi! Isliye error:
// [Link]([Link]); // ❌ COMPILE ERROR

// Yeh valid hai — kyunki hum khud object bana rahe hain
Counter temp = new Counter("temp");
[Link]([Link]); // ✅
}
}

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter("Rakesh");
Counter c2 = new Counter("Priya");

// Jab showCount() call ho — this kaun hoga? c1? c2?


// Java ke paas koi answer nahi — isliye this allowed nahi!
[Link](); // count = 3 (c1, c2, aur temp)
}
}

3.4 — Complete Access Rules Matrix


Yeh matrix sabse important reference hai — exam mein direct question aa sakta hai:

Context / Situation Static Method Instance Member Access this / super


Access
Static method ke andar ✅ Directly call kar ❌ NAHI — object ka pata ❌ Use NAHI kar
sakte nahi sakte
Instance method ke ✅ ✅ Directly — this object ✅ Available hai
andar [Link]() hai
se
Static block ke andar ✅ Directly call kar ❌ NAHI — object ka pata ❌ Use NAHI kar
sakte nahi sakte
Instance block ke andar ✅ ✅ Directly available ✅ Available hai
[Link]()
se
main() method ke andar ✅ Directly ya ❌ Object banao phir ❌ Use NAHI kar
[Link]() access karo sakte
Constructor ke andar ✅ ✅ this. se access hota hai ✅ super() call kar
[Link]() sakte
se

🔷 Method Hiding — Static Methods Override Kyun Nahi Hote?


Yeh ek bahut tricky aur important concept hai jo almost har Java interview mein aata hai. Hum jaante hain ki
Instance methods OVERRIDE ho sakte hain. Lekin Static Methods OVERRIDE NAHI hote — inhe METHOD
HIDING kehte hain. Fark kya hai? Aao detail mein samjhein.

4.1 — Override vs Hiding — Side by Side


// Method Hiding vs Method Overriding — Side by Side
// Method Overriding (Instance Methods) — Runtime decide
class Animal {
// Instance method — OVERRIDE hoga
void makeSound() {
[Link]("Animal: Generic awaaz...");
}

// Static method — HIDE hoga (override nahi)


static void category() {
[Link]("Animal: I am an Animal (static).");
}
}

class Dog extends Animal {


// ✅ Override — @Override annotation lagao
@Override
void makeSound() {
[Link]("Dog: Bhau Bhau!");
}

// This is METHOD HIDING — NOT overriding


// @Override lagaane par COMPILE ERROR aayega!
static void category() {
[Link]("Dog: I am a Dog (static).");
}
}

public class Main {


public static void main(String[] args) {

[Link]("=== Instance Method (Overriding) ===");


Animal a1 = new Dog(); // Upcasting
[Link](); // Dog ka method → Runtime decides → Bhau Bhau!
// WHY? Runtime polymorphism — JVM actual object type dekh ke decide karta hai

[Link]("\n=== Static Method (Hiding) ===");


Animal a2 = new Dog(); // Upcasting
[Link](); // Animal ka method → Compile time decides!
// WHY? Static binding — reference type (Animal) decide karta hai

Animal a3 = new Animal();


[Link](); // Animal ka method

Dog d = new Dog();


[Link](); // Dog ka method (reference type = Dog)

[Link]("\n=== Direct Class Call (Best Practice) ===");


[Link](); // Animal ka — clearly pata chalta hai
[Link](); // Dog ka — clearly pata chalta hai
}
}

// Output:
// === Instance Method (Overriding) ===
// Dog: Bhau Bhau! ← OBJECT TYPE decide karta hai (Dog)

// === Static Method (Hiding) ===


// Animal: I am an Animal ← REFERENCE TYPE decide karta hai (Animal)
// Animal: I am an Animal ← Reference Animal — Animal ka chala
// Dog: I am a Dog ← Reference Dog — Dog ka chala

// === Direct Class Call ===


// Animal: I am an Animal
// Dog: I am a Dog

🎯 Key Difference — Interview Method Overriding (Instance): OBJECT TYPE decide karta hai —
Answer Runtime Polymorphism
Animal a = new Dog(); → [Link]() → Dog ka sound()
chalta hai

Method Hiding (Static): REFERENCE TYPE decide karta hai —


Compile-time Binding
Animal a = new Dog(); → [Link]() → Animal ka category()
chalta hai!

Isliye static methods ko override NAHI karna chahiye — confusing


hota hai.
Hamesha [Link]() se call karo — clearly pata
chalta hai.

4.2 — @Override aur Static — Compiler Error


// @Override on static method → Compile Error
// @Override + static method → COMPILE ERROR
class Parent {
static void display() {
[Link]("Parent static display");
}
}

class Child extends Parent {

// ❌ COMPILE ERROR: Method does not override method from its superclass
// @Override ← Yeh annotation static method par NAHI lag sakta
static void display() {
[Link]("Child static display");
}
// Yeh Override nahi hai — yeh ek nayi 'hidden' method hai

// ❌ YEH BHI ERROR dega — static method ko override karne ki koshish


// @Override
// static void display() { ... } // COMPILE ERROR!
}

// Summary:
// Instance method + @Override → ✅ Valid Override — Runtime Polymorphism
// Static method + no @Override → ✅ Valid Hiding — Compile-time Binding
// Static method + @Override → ❌ COMPILE ERROR — not allowed
🔷 Utility Classes — Static Methods Ka Best Use Case
Utility Class ek aisi class hai jisme sirf static methods hote hain — koi state (instance variables) nahi hoti. Iska
object banana meaningless hota hai — isliye constructor private rakha jaata hai. Java khud kai utility classes
provide karta hai.

5.1 — Java ke Built-in Utility Classes


Class Package Important Static Methods
Math [Link] [Link](), [Link](), [Link](), [Link](),
[Link](), [Link](), [Link]()
Arrays [Link] [Link](), [Link](), [Link](),
[Link](), [Link]()
Collections [Link] [Link](), [Link](),
[Link](), [Link](),
[Link]()
Objects [Link] [Link](), [Link](), [Link](),
[Link]()
String [Link] [Link](), [Link](), [Link]() — class
final hai, kuch static methods
Integer [Link] [Link](), [Link](),
[Link](), [Link]()

5.2 — Apna Custom Utility Class Banana


// Custom StringUtils Utility Class
// Custom Utility Class — Real Project Pattern
// private constructor — object banana BAND
public final class StringUtils {

// Private constructor — koi object nahi bana sakta


private StringUtils() {
throw new AssertionError("StringUtils is a utility class — no objects!");
}

// ── String check methods ──


public static boolean isNullOrEmpty(String s) {
return s == null || [Link]().isEmpty();
}
public static boolean isValidEmail(String email) {
if (isNullOrEmpty(email)) return false;
return [Link]("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
}

public static boolean isValidIndianMobile(String phone) {


if (isNullOrEmpty(phone)) return false;
return [Link]("^[6-9]\\d{9}$");
}

// ── String transformation ──
public static String capitalize(String s) {
if (isNullOrEmpty(s)) return "";
return [Link](0,1).toUpperCase() + [Link](1).toLowerCase();
}

public static String toCamelCase(String words) {


if (isNullOrEmpty(words)) return "";
String[] parts = [Link]().split("\\s+");
StringBuilder sb = new StringBuilder(parts[0].toLowerCase());
for (int i = 1; i < [Link]; i++) {
[Link](capitalize(parts[i]));
}
return [Link]();
}

public static String maskPhone(String phone) {


if (isNullOrEmpty(phone) || [Link]() < 4) return phone;
return "XXXXXX" + [Link]([Link]() - 4);
}

public static String maskEmail(String email) {


if (!isValidEmail(email)) return email;
int at = [Link]('@');
return [Link](0,2) + "****" + [Link](at);
}

// ── Number utils ──
public static String formatCurrency(double amount) {
return [Link]("₹%,.2f", amount);
}

public static boolean isPalindrome(String s) {


if (isNullOrEmpty(s)) return false;
String clean = [Link]().replaceAll("[^a-z0-9]", "");
return [Link](new StringBuilder(clean).reverse().toString());
}
}

public class Main {


public static void main(String[] args) {

// ── Koi object nahi — seedha class se call karo! ──


[Link]([Link]("")); // true
[Link]([Link]("Rakesh")); // false

[Link]([Link]("rakesh@[Link]")); // true
[Link]([Link]("invalid")); // false

[Link]([Link]("9876543210")); // true
[Link]([Link]("1234567890")); // false

[Link]([Link]("hELLO wORLD")); // Hello world


[Link]([Link]("user first name")); // userFirstName

[Link]([Link]("9876543210")); // XXXXXX3210
[Link]([Link]("rakesh@[Link]")); // ra****@[Link]

[Link]([Link](150000.50)); // ₹1,50,000.50
[Link]([Link]("A man a plan a canal Panama")); // true

// ❌ Yeh compile error nahi deta but logically wrong — avoid karo:
// StringUtils obj = new StringUtils(); // AssertionError throw hoga!
}
}

🔷 Static aur Inheritance — Aur Bhi Rules!


Static methods aur inheritance ke saath kuch important rules hain jo often confuse karte hain. Ek ek karke
samjhein:

6.1 — Static Methods Inherit Hote Hain — lekin Override Nahi


// Static Inheritance — Inherit hota hai par Override nahi
// Static methods inherit hote hain — accessible hain child se
class Vehicle {
static String type = "Vehicle";

static void describe() {


[Link]("Main ek " + type + " hun.");
}

void move() {
[Link]("Vehicle move kar raha hai.");
}
}

class Car extends Vehicle {


// describe() inherit hui hai — [Link]() call kar sakte hain
// Lekin agar Car mein describe() likhein toh woh HIDING hai, Override nahi

void honk() {
[Link]("Car: Beep Beep!");
}
}

public class Main {


public static void main(String[] args) {

// ✅ Inherited static method — Car ke through bhi accessible


[Link](); // Works! — prints Vehicle ka describe()
[Link](); // Same result

// Best practice: always use the class that DEFINES the method
// [Link]() → clearly batata hai ki yeh Vehicle ka hai

[Link]([Link]); // 'Vehicle' — inherited static var


[Link]([Link]); // 'Vehicle' — same thing
}
}

// Output:
// Main ek Vehicle hun.
// Main ek Vehicle hun.
// Vehicle
// Vehicle

6.2 — Complete Static + OOP Interaction Rules


🔵 Static Context 🟠 Instance Context
Static variable — directly access Static variable — directly access (ya ClassName.
se)
Static method — directly call Static method — [Link]() se call
karo
Instance variable — ❌ ERROR Instance variable — directly access (this.
optional)
Instance method — ❌ ERROR Instance method — directly call (this. optional)
this keyword — ❌ BANNED this keyword — ✅ available hai
super keyword — ❌ BANNED super keyword — ✅ available hai
Object banake instance access — ✅ OK Object banake doosre class access — ✅ OK
Override — ❌ Nahi hota (Method Hiding) Override — ✅ Runtime Polymorphism

🏗️Complete Real-World Example — Student Grade System


Ek complete example dekhte hain jisme Static Methods, Access Rules, aur Utility pattern sab ek saath use hue hain
— ek Student Grade Management System:

// Complete Grade System — Static Methods + Utility Class + Access Rules


//
════════════════════════════════════════════════════
══
// Student Grade System — Static Methods + Access Rules
//
════════════════════════════════════════════════════
══

// Utility class — grade calculation logic


final class GradeUtils {
private GradeUtils() {} // No objects!

static String getGrade(double marks) {


if (marks >= 90) return "A+";
if (marks >= 80) return "A";
if (marks >= 70) return "B";
if (marks >= 60) return "C";
if (marks >= 40) return "D";
return "F";
}

static String getRemarks(double marks) {


if (marks >= 90) return "Outstanding! 🏆";
if (marks >= 80) return "Excellent! ⭐";
if (marks >= 70) return "Good! 👍";
if (marks >= 60) return "Average. Keep working!";
if (marks >= 40) return "Pass — but improve karo.";
return "Fail — mehnat karo! 📚";
}

static double calculatePercentage(double[] marks, int totalPerSubject) {


double sum = 0;
for (double m : marks) sum += m;
return (sum / ([Link] * totalPerSubject)) * 100;
}

static double findHighest(double[] marks) {


double max = marks[0];
for (double m : marks) if (m > max) max = m;
return max;
}

static double findLowest(double[] marks) {


double min = marks[0];
for (double m : marks) if (m < min) min = m;
return min;
}
}
// Student class — mix of static and instance
class Student {

// Static variables — class level info


static String schoolName = "Patna Science Academy";
static String examYear = "2024-25";
static int totalStudents = 0;
static double classAverage = 0;
static double totalMarksSum = 0;

// Instance variables — per student


int rollNo;
String name;
double[] subjectMarks; // [Math, Science, English, Hindi, SST]
double percentage;

// Constructor
Student(int rollNo, String name, double[] marks) {
[Link] = rollNo;
[Link] = name;
[Link] = marks;
[Link] = [Link](marks, 100);

// Update class-level static data


totalStudents++;
totalMarksSum += [Link];
classAverage = totalMarksSum / totalStudents; // rolling average
}

// Instance method — individual report


void printReport() {
String[] subjects = {"Math", "Science", "English", "Hindi", "SST"};
[Link]("\
n╔══════════════════════════════════════════╗");
[Link]( "║ %-40s ║%n", schoolName);
[Link]( "║ Year: %-34s ║%n", examYear);

[Link]("╠═════════════════════════════════════════
═╣");
[Link]( "║ Roll: %-5d Name: %-24s ║%n", rollNo, name);
[Link]("╠═════════════════════════════════════════
═╣");
for (int i = 0; i < [Link]; i++) {
[Link]("║ %-10s : %5.1f %-20s ║%n",
subjects[i], subjectMarks[i],
[Link](subjectMarks[i])); // Static util call!
}

[Link]("╠═════════════════════════════════════════
═╣");
[Link]( "║ Percentage : %.2f%% Grade: %-12s ║%n",
percentage, [Link](percentage));
[Link]( "║ Remarks : %-27s ║%n",
[Link](percentage));
[Link]( "║ Best Score : %.1f | Lowest: %-13.1f ║%n",
[Link](subjectMarks),
[Link](subjectMarks));

[Link]("╚═════════════════════════════════════════
═╝");
}

// Static method — class-level summary


static void printClassSummary() {
[Link]("\n📊 CLASS SUMMARY — " + schoolName);
[Link](" Year : " + examYear);
[Link](" Total Students: " + totalStudents);
[Link]( " Class Average : %.2f%% (%s)%n",
classAverage, [Link](classAverage));
[Link](" " + [Link](classAverage));
// Note: static method mein instance vars (rollNo, name) access nahi kar sakte!
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student(1, "Rakesh Kumar",
new double[]{92, 88, 76, 85, 91});

Student s2 = new Student(2, "Priya Sharma",


new double[]{78, 82, 90, 74, 80});
Student s3 = new Student(3, "Ajay Verma",
new double[]{55, 62, 48, 70, 60});

[Link]();
[Link]();
[Link]();

[Link](); // Static method — class se call!


}
}

⚠️Common Mistakes — Jinse Bachna Hai!


Yeh mistakes beginners aur experienced developers dono karte hain. Inhe ek baar padh lo — fir galti mat karna:

// Common Mistakes aur unke Fixes


//
════════════════════════════════════════════════════
══
// COMMON MISTAKES aur unke CORRECT versions
//
════════════════════════════════════════════════════
══

class CommonMistakes {
static int staticX = 10;
int instanceY = 20;

// ❌ MISTAKE 1: Static method mein instance var access


static void mistake1() {
// [Link](instanceY); // COMPILE ERROR!
// FIX: Object banao
CommonMistakes obj = new CommonMistakes();
[Link]([Link]); // ✅
}

// ❌ MISTAKE 2: Object se static variable access (misleading)


void mistake2() {
CommonMistakes obj = new CommonMistakes();
// [Link] = 99; // Works but IDE warning aata hai!
// FIX: Class naam se access karo
[Link] = 99; // ✅ Clear aur correct
}

// ❌ MISTAKE 3: Static method ko override karne ki koshish


static void mistake3() {
[Link]("Parent static");
}
// Child mein agar same naam ka static method likhein — METHOD HIDING hai!
// @Override lagaane se COMPILE ERROR aata hai
}

// ❌ MISTAKE 4: Utility class ka object banana


// Math m = new Math(); // ❌ Math is abstract — object nahi ban sakta
// FIX: seedha use karo:
// [Link](16); // ✅

// ❌ MISTAKE 5: Static context mein this use karna


class MyClass {
int x = 5;
static void show() {
// [Link](this.x); // ❌ COMPILE ERROR
MyClass temp = new MyClass();
[Link](temp.x); // ✅ Object se access karo
}
}

// ❌ MISTAKE 6: Static variable ko instance variable ki tarah sochna


class Counter {
static int count = 0;
Counter() { count++; }
}
// Counter c1 = new Counter();
// Counter c2 = new Counter();
// [Link] → 2 (NOT 1! — shared hai dono mein)
// [Link] → 2 (dono ek hi memory dekh rahe hain)
📋 Quick Revision — Exam aur Interview ke Liye

Sabse Important Points — Pakka Yaad Karo


• static method: object banaye bina call — [Link]()
• main() static kyun: JVM object banaye bina call karta hai — chicken-egg problem avoid
• Static → Static: directly access kar sakte hain
• Static → Instance: ❌ NAHI — compile error — object banao phir access karo
• Instance → Static: ✅ [Link]() se call kar sakte hain
• this in static: ❌ BANNED — static mein koi 'current object' nahi hota
• super in static: ❌ BANNED — super bhi object-level concept hai
• Method Hiding: static method child mein redefine → hiding (override NAHI) — reference type decides
• Method Override: instance method child mein redefine → override — object type decides
• @Override + static: COMPILE ERROR — static methods override nahi ho sakte
• Utility class: private constructor + all static methods — Math, Arrays, Collections
• Best practice: [Link]() — object se static call misleading hota hai

Topic Rule / Syntax Hinglish Yaad-Sutra


static method static returnType method() Object banaye bina call hota —
[Link]()
Static → static Directly call kar sakte Apne ghar ke log — koi problem nahi
Static → instance ❌ NAHI — compile error Bina ghar ke kisi ka saman nahi pakad sakte
Instance → static ✅ [Link]() se Bahar ka banda ghar mein aa sakta hai
this in static ❌ Allowed NAHI this ka matlab 'current object' — static mein
object hi nahi!
super in static ❌ Allowed NAHI super bhi object-level concept hai — static
mein banned
Override static? ❌ Override NAHI hota — Child mein same naam → new method —
hiding parent wala chhupta hai
Method hiding Parent ref → parent static Reference type decide karta hai — object type
runs nahi!
Utility class private constructor + static Math, Collections, Arrays — yahi pattern
methods
main() bhi static public static void JVM object banaye bina main() call karta hai
main(String[]) isliye static!

toString()
-------

1. toString() is a predefined method of the Object class in Java.


2. Since every Java class implicitly extends the Object class, every class automatically gets the toString()
method.
3. The main purpose of toString() is to return a String representation of an object.
4. Whenever we print an object using [Link](object);, Java automatically calls the object's
toString() method.
5. This automatic method call happens because the println() method internally invokes [Link]() for
every object.
6. If we do not override the toString() method, Java uses the default implementation provided by the Object
class.
7. The default implementation returns the fully qualified class name followed by @ and the hexadecimal
hash code of the object.
8. For example, the output may look like Student@5acf9800, which is not useful for understanding the
object's data.
9. This output is not the memory address of the object; it is the class name along with the hexadecimal form
of the object's hash code.
10. In real-world applications, developers usually override toString() to return meaningful information about
the object.
11. By overriding it, we can display important instance variables like id, name, salary, or email instead of the
default output.
12. This makes the object easier to understand while printing, debugging, or logging.
13. Overriding toString() is an example of Runtime Polymorphism (Method Overriding) because the child
class provides its own implementation.
14. When [Link](object); is executed, Java decides at runtime whether to use the default toString()
or the overridden version.
15. Developers frequently use toString() during debugging to check the current values stored inside an object.
16. It is also widely used in logging frameworks such as Log4j and SLF4J because logs become more
readable when objects have meaningful toString() implementations.
17. In Spring Boot and other enterprise applications, developers often print objects received from APIs or
databases, and toString() helps display their contents clearly.
18. During testing, printing an object with toString() helps verify that all object fields contain the expected
values.
19. A good toString() implementation should include only the important fields of the object and present them in
a clear format.
20. Sensitive information such as passwords, OTPs, API keys, or secret tokens should never be included in
the toString() method because they may appear in logs.
21. Calling [Link](object); and [Link]([Link]()); produces the same output
because println() automatically invokes toString().
22. The @Override annotation is recommended when overriding toString() because it allows the compiler to
verify that the method signature is correct.
23. Every Java developer should know how and when to override toString() because it is one of the most
commonly used methods inherited from the Object class.
24. A well-written toString() method improves code readability, simplifies debugging, makes logs more
meaningful, and helps developers understand the state of an object quickly.
25. In simple words, toString() acts like an identity card of an object, because whenever someone prints the
object, it decides what information should be shown to the user or developer.

Example
class Student {

int id;
String name;

Student(int id, String name) {


[Link] = id;
[Link] = name;
}

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

public class Test {

public static void main(String[] args) {

Student s = new Student(101, "Rakesh");

[Link](s); // Automatically calls toString()


[Link]([Link]()); // Explicitly calls toString()

}
}
Output
Student{id=101, name='Rakesh'}
Student{id=101, name='Rakesh'}

Developer Interview Notes

 toString() belongs to the Object class.


 Every class inherits it automatically because every class extends Object.
 [Link](object) internally calls [Link]().
 The default implementation prints ClassName@HexHashCode.
 Developers override it to print meaningful object details.
 It is heavily used for debugging, logging, testing, and inspecting objects in enterprise applications like
Spring Boot and Hibernate.

final keyword:
---------

1. final is a non-access modifier in Java that is used to restrict modification, inheritance, or overriding.
2. It can be applied to variables, methods, and classes.
3. The meaning of final depends on where it is used.
4. When a variable is declared as final, its value can be assigned only once.
5. After initialization, a final variable cannot be reassigned to another value.
6. For this reason, final variables are often used to represent constants.
7. By convention, constant variable names are written in UPPER_CASE.
8. A final variable can be initialized either at the time of declaration or inside a constructor (if it is an instance
variable).
9. If a final variable is not initialized, the compiler generates an error because it must receive exactly one
value.
10. When a reference variable is declared as final, the reference cannot point to another object.
11. However, the object's internal data can still be modified if the object's fields are mutable.
12. Therefore, final makes the reference immutable, not necessarily the object itself.
13. When a method is declared as final, it cannot be overridden by a subclass.
14. This ensures that the original implementation of the method remains unchanged in all child classes.
15. Developers use final methods when they want to protect important business logic from being modified.
16. However, a final method can still be inherited and called by child classes.
17. When a class is declared as final, no other class can extend it.
18. This means inheritance is completely prevented for that class.
19. Classes like String, Math, and wrapper classes (such as Integer) are final because their behavior should
not be changed.
20. Developers use final classes to improve security, maintain consistency, and prevent unintended
inheritance.
21. Using final also helps the compiler understand that certain values or behaviors will never change.
22. This can allow the JVM to perform small performance optimizations in some situations.
23. In real-world applications, developers use final for constants, configuration values, utility classes, and
methods that should never be overridden.
24. The final keyword improves code reliability because it prevents accidental modification of important code.
25. In simple words, final means "this cannot be changed anymore," whether it is a variable's value, a
method's implementation, or a class's inheritance.

1. final Variable

A final variable can be assigned only once.

class Demo {
final int AGE = 25;

public static void main(String[] args) {


Demo d = new Demo();
[Link]([Link]);

// [Link] = 30; // Compile-time Error


}
}

Output

25

final Reference Variable


class Student {
String name = "Rakesh";
}

public class Test {

public static void main(String[] args) {

final Student s = new Student();


[Link] = "Rahul"; // Allowed

// s = new Student(); // Compile-time Error

[Link]([Link]);
}
}

Output

Rahul

Developer Note: The object can change, but the reference cannot point to another object.

2. final Method

A final method cannot be overridden.

class Parent {

final void display() {


[Link]("Parent Display");
}
}

class Child extends Parent {

// Compile-time Error
// void display() { }

Developer Note: Use final methods to protect important business logic from being changed by subclasses.

3. final Class

A final class cannot be extended.

final class Animal {

// Compile-time Error
// class Dog extends Animal { }

Developer Note: String is a final class, so no one can inherit from it and change its behavior.
Real-World Developer Uses
1. Constants
class AppConfig {

public static final double PI = 3.14159;


public static final String COMPANY_NAME = "OpenAI";

2. Configuration Values
public static final int MAX_LOGIN_ATTEMPTS = 3;

These values should never change while the application is running.

3. Secure Business Logic


class PaymentService {

public final void processPayment() {


[Link]("Payment Processed");
}

No subclass can override the payment logic.

4. Utility Classes
final class MathUtil {

private MathUtil() { }

Developers make utility classes final so nobody can extend them.

Interview Notes

 final is a non-access modifier.


 It can be applied to variables, methods, and classes.
 A final variable can be assigned only once.
 A final reference cannot point to another object, but the object's state may still change.
 A final method cannot be overridden.
 A final class cannot be inherited.
 public static final is commonly used to create constants.
 final helps write secure, reliable, and maintainable code by preventing unwanted changes.

static final Variable in Java

1. A static final variable is a variable that belongs to the class and whose value cannot be changed after
initialization.
2. It combines the behavior of both the static and final keywords.
3. The static keyword means the variable belongs to the class, not to individual objects.
4. Therefore, only one copy of the variable is created in memory, regardless of how many objects are
created.
5. The final keyword means the variable can be assigned only once.
6. After a static final variable is initialized, its value cannot be modified during the program's execution.
7. Because of these properties, static final variables are mainly used to define constants.
8. A constant is a value that remains the same throughout the lifetime of the application.
9. Developers usually write static final variable names in UPPER_CASE to distinguish them from normal
variables.
10. Since the variable belongs to the class, it can be accessed directly using the class name without creating
an object.
11. This improves memory efficiency because every object shares the same constant value.
12. static final variables are initialized when the class is loaded into the JVM, before any object is created.
13. Once initialized, the JVM does not allow the value to be reassigned.
14. This provides safety because important values cannot be accidentally changed.
15. In Java, many predefined constants are declared as public static final, such as [Link].
16. Developers use static final variables for values like application names, tax rates, maximum limits, API
versions, and configuration constants.
17. In Spring Boot projects, constants such as API URLs, status codes, role names, and message keys are
often declared as static final.
18. Using static final improves code readability because meaningful names replace hardcoded values (also
called magic numbers).
19. If a constant value needs to change, the developer updates it in one place instead of searching the entire
project.
20. This reduces bugs and makes the application easier to maintain.
21. The compiler may also optimize the use of static final constants because their values are known at compile
time.
22. A static final variable does not require an object for access because it belongs to the class itself.
23. In simple words, static means "one copy shared by all objects," and final means "that copy can
never change."
24. Therefore, a static final variable is a class-level constant that is shared by every object and remains
unchanged throughout the program.

Syntax
class ClassName {

static final dataType VARIABLE_NAME = value;

}
Example 1: Application Constant
class AppConfig {

static final String APP_NAME = "My CRM";

public static void main(String[] args) {

[Link](AppConfig.APP_NAME);

// APP_NAME = "New CRM"; // Compile-time Error

}
}

Output

My CRM

Example 2: Shared by All Objects


class Employee {

int id;
String name;

static final String COMPANY = "OpenAI";

Employee(int id, String name) {


[Link] = id;
[Link] = name;
}
}

public class Test {

public static void main(String[] args) {

Employee e1 = new Employee(101, "Rakesh");


Employee e2 = new Employee(102, "Rahul");

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

}
}

Output

OpenAI
OpenAI
OpenAI

Notice that both objects share the same COMPANY variable because it belongs to the class.

Real-World Developer Uses


1. Application Name
public static final String APP_NAME = "Inventory Management System";
2. Maximum Login Attempts
public static final int MAX_LOGIN_ATTEMPTS = 3;
3. API Version
public static final String API_VERSION = "v1";
4. User Roles
public static final String ROLE_ADMIN = "ADMIN";
public static final String ROLE_USER = "USER";
5. HTTP Status Codes (Custom)
public static final int SUCCESS = 200;
public static final int NOT_FOUND = 404;

Developer Interview Notes

 static → Belongs to the class, so only one copy exists.


 final → Value can be assigned only once.
 static final → Creates a class-level constant.
 It is accessed using the class name, not an object.
 It is initialized when the class is loaded by the JVM.
 It is commonly used for constants like [Link], configuration values, limits, role names, and application
settings.
 By convention, static final constant names are written in UPPER_CASE.
 Memory Tip: A normal variable creates a copy in every object, a static variable creates one shared copy,
and a static final variable creates one shared copy whose value can never change. This is why it is ideal for
constants used throughout an application.

Java Programming Notes — Static Keyword Part 2 • Static Methods • Access Rules • Method Hiding • Utility
Classes | Hinglish Edition 🇮🇳

You might also like