0% found this document useful (0 votes)
4 views22 pages

Java Static Keyword p1

The document explains the 'static' keyword in Java, which allows variables and methods to be shared across all instances of a class without needing to create an object. It covers static variables, methods, blocks, and their differences from instance variables, along with memory allocation details and real-life analogies. Additionally, it provides examples of when to use static variables and the execution order of static blocks in Java.

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)
4 views22 pages

Java Static Keyword p1

The document explains the 'static' keyword in Java, which allows variables and methods to be shared across all instances of a class without needing to create an object. It covers static variables, methods, blocks, and their differences from instance variables, along with memory allocation details and real-life analogies. Additionally, it provides examples of when to use static variables and the execution order of static blocks in Java.

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


Part — 1
Static Variable • Instance vs Static • Memory Model • Static Block • Execution Order

🔷 static Keyword — Pehle Seedha Concept Samjho


Java mein OOP ke rules kehte hain: 'pehle object banao, phir kaam karo'. Lekin kabhi kabhi kuch cheezein aisi hoti
hain jo SABHI objects mein SAME HOTI HAIN — ya jinhe object banaaye BINA use karna ho. Iske liye Java ne ek
special keyword diya hai — static.

static ka matlab hai: 'Yeh cheez class ki hai — kisi ek object ki nahi.' Static cheezein class load hote hi memory
mein aa jaati hain — bina ek bhi object banaye. Aur sab objects unhe share karte hain.

Static keyword:
It is a non access modifier.
Memory efficient program.
Use: With variable(class variable), Method, Block & Nested class
Not related to Object

Static keywords used with:


Variable (Class variable)
Method ()
Block
Nested Clas
Java mein static yeh chaar jagah lagta hai:

static Variable static Method static Block static Class (Nested)

🔷 Static Variable — Class Ki Shared Property


Static Variable woh variable hai jo kisi ek object ka nahi — PURI CLASS KA hota hai. Jitne bhi objects us class ke
hoon, sab ek hi static variable share karte hain. Kisi ek ne value change ki — sab ko reflect hoti hai!

2.1 — Real Life Analogy — School Ka Notice Board 📋


Sochte hain ek School hai — 'Patna Public School'. School mein 500 students hain. Ab sochte hain ek Notice
Board hai main gate par.

👤 Instance Variable 📋 Static Variable

Har student ka naam, roll number, marks — yeh School ka naam, principal ka naam, school ka
sirf US student ka hai. Dusre student ko is se koi address — yeh SABHI 500 students ke liye
matlab nahi. SAME hai. Ek jagah likha — sab padhte hain.
→ Instance Variable: Har object ka APNA → Static Variable: Sab objects ka SHARED
data data

2.2 — Static vs Instance Variable — Code mein Difference


// Static vs Instance Variable — Student Class
// Static vs Instance Variable — Clear Comparison
class Student {

// ── STATIC variable — class ka hai, sab share karte hain ──


static String schoolName = "Patna Public School";
static int totalStudents = 0; // Counter — har naye object par badhega

// ── INSTANCE variables — har object ka apna ──


int rollNumber;
String name;
int marks;

// Constructor
Student(int roll, String name, int marks) {
[Link] = roll;
[Link] = name;
[Link] = marks;
totalStudents++; // Har naya object bana → counter badhao
// Note: static variable ko this. ki zaroorat nahi
}

void display() {
[Link]("School: " + schoolName); // Shared value
[Link]("Name: " + name + " | Roll: " + rollNumber + " | Marks: " + marks);
[Link]("Total Students So Far: " + totalStudents);
[Link]("---");
}
}

public class Main {


public static void main(String[] args) {

[Link]("Koi object banane se pehle:");


[Link]("School: " + [Link]); // ✅ Class se access
[Link]("Total Students: " + [Link]); // 0
[Link]("===");

Student s1 = new Student(101, "Rakesh Kumar", 88);


Student s2 = new Student(102, "Priya Sharma", 92);
Student s3 = new Student(103, "Ajay Verma", 75);

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

// Static variable change karo — SABKO dikhega!


[Link]("School ka naam badal rahe hain...");
[Link] = "Patna Central School"; // Sahi tarika
// [Link] = "XYZ"; // Ye bhi kaam karta hai par sahi nahi — warning aata hai

[Link]("s1 ko school: " + [Link]); // Patna Central School


[Link]("s2 ko school: " + [Link]); // Patna Central School
[Link]("s3 ko school: " + [Link]); // Patna Central School
// Dekho — teeno ko naya naam dikh raha hai! Ek hi copy hai memory mein.
}
}

// Output:
// Koi object banane se pehle:
// School: Patna Public School
// Total Students: 0
// ===
// School: Patna Public School | Name: Rakesh Kumar | Roll: 101 | Marks: 88
// Total Students So Far: 1
// School: Patna Public School | Name: Priya Sharma | Roll: 102 | Marks: 92
// Total Students So Far: 2
// School: Patna Public School | Name: Ajay Verma | Roll: 103 | Marks: 75
// Total Students So Far: 3
// School ka naam badal rahe hain...
// s1 ko school: Patna Central School
// s2 ko school: Patna Central School
// s3 ko school: Patna Central School
🧠 Key Observation Dekho: Static variable 'schoolName' ek baar change kiya — aur s1, s2, s3 teeno
ko naya value
dikh raha hai! Kyunki memory mein sirf EK copy hai — teeno objects same jagah
dekh rahe hain.

Instance variable 'marks' alag alag hai — [Link]=88, [Link]=92,


[Link]=75.
Ek ka marks badle toh doosre par koi asar nahi.

2.3 — Memory mein Kya Hota Hai? — JVM Memory Model


Yeh samajhna bahut zaroori hai ki static aur instance variables memory mein ALAG ALAG jagah store hote hain.
JVM ki memory do important areas mein divide hoti hai:

Static variables JVM ke Method Area (ya Class Area) mein store hote hain — yeh area class ke load hone par ek
baar allocate hota hai aur program khatam hone tak rehta hai. Instance variables Heap mein store hote hain — har
naye object ke saath naya allocation.

2.4 — Kab Static Variable Use Karein? — Real Use Cases


Har variable ko static nahi banana chahiye! Sirf tabhi use karo jab koi value SABHI objects mein SAME ho ya
shared counter/configuration ho:

// Static Variable — 4 Real Use Cases


// Static Variable — 4 Real Use Cases
// ── Use Case 1: Object Counter
────────────────────────────────────
class Connection {
static int activeConnections = 0;
String host;

Connection(String host) {
[Link] = host;
activeConnections++;
[Link]("Connected to: " + host + " | Total: " + activeConnections);
}

void close() {
activeConnections--;
[Link]("Disconnected from: " + host + " | Total: " + activeConnections);
}
}

// ── Use Case 2: Shared Configuration ─────────────────────────────


class AppConfig {
static String dbUrl = "jdbc:mysql://localhost:3306/mydb";
static String appVersion = "v2.1.0";
static int maxPoolSize = 10;
// Poori application mein ek hi config — sab classes share karein
}

// ── Use Case 3: Unique ID Generator ──────────────────────────────


class Order {
static int nextOrderId = 1000; // Starting from 1000
int orderId;
String product;

Order(String product) {
[Link] = nextOrderId++; // Post-increment — pehle assign, phir badhao
[Link] = product;
[Link]("Order Created — ID: " + orderId + " | Item: " + product);
}
}
// ── Use Case 4: Singleton Pattern ────────────────────────────────
class DatabaseManager {
private static DatabaseManager instance = null; // Sirf ek instance

private DatabaseManager() {
[Link]("Database connection establish ho rahi hai...");
}

// Agar instance nahi hai toh banao — warna existing return karo
public static DatabaseManager getInstance() {
if (instance == null) {
instance = new DatabaseManager();
}
return instance;
}

public void query(String sql) {


[Link]("Query execute: " + sql);
}
}

public class Main {


public static void main(String[] args) {
// Use Case 1: Connection counter
Connection c1 = new Connection("[Link]");
Connection c2 = new Connection("[Link]");
[Link]();
[Link]("Active now: " + [Link]);

[Link]("---");

// Use Case 2: Config access


[Link]("DB: " + [Link]);
[Link]("Version: " + [Link]);

[Link]("---");

// Use Case 3: Auto ID


new Order("Laptop");
new Order("Phone");
new Order("Tablet");

[Link]("---");

// Use Case 4: Singleton


DatabaseManager db1 = [Link]();
DatabaseManager db2 = [Link](); // Same object!
[Link]("SELECT * FROM users");
[Link]("Same instance? " + (db1 == db2)); // true
}
}

// Output:
// Connected to: [Link] | Total: 1
// Connected to: [Link] | Total: 2
// Disconnected from: [Link] | Total: 1
// Active now: 1
// ---
// DB: jdbc:mysql://localhost:3306/mydb | Version: v2.1.0
// ---
// Order Created — ID: 1000 | Item: Laptop
// Order Created — ID: 1001 | Item: Phone
// Order Created — ID: 1002 | Item: Tablet
// ---
// Database connection establish ho rahi hai...
// Query execute: SELECT * FROM users
// Same instance? true

2.5 — Instance Variable vs Static Variable — Full Comparison


👤 Instance Variable 📊 Static Variable
Har object ka APNA alag copy hota hai Sab objects mein EK hi shared copy hoti hai
Object ke saath Heap mein banta hai Class load hone par Method Area mein banta hai
Object ke saath garbage collect hota hai Program khatam hone tak memory mein rehta hai
Access: [Link] Access: [Link] (best practice)
this keyword se access hota hai this se access nahi — class level hai
Jab tak object hai, tab tak hai Jab tak class loaded hai, tab tak hai
Example: name, age, marks, id Example: count, schoolName, appVersion
Kab use karein: Per-object unique data Kab use karein: Shared data, counters, config

🔷 Static Block — Class Load Hote Hi Chalne Wala Code


Static Block Java ka ek special feature hai jisme tum ek block of code likh sakte ho jo class load hone par
AUTOMATICALLY execute hota hai — sirf EK BAAR — koi bhi object banane se pehle, main() method se bhi
pehle!

Static Block = Woh security guard jo factory gate par khada hai. Factory khulte hi — pehle wahi check karta hai,
pehle wahi kaam karta hai — sabse pehle, hamesha. Koi worker (object) andar aaye — baad mein!

3.1 — Static Block ka Syntax aur Basic Example


// Static Block — Basic Example aur Execution Order
// Static Block — Basic Syntax
class MyClass {

static int x;
static String message;

// Static Block — class load hote hi chalega


static {
[Link]("Static Block Execute Ho Raha Hai!");
x = 42;
message = "Hello from static block!";
[Link]("x initialized: " + x);
}

MyClass() {
[Link]("Constructor call ho raha hai.");
}
}

public class Main {


public static void main(String[] args) {
[Link]("main() shuru ho gaya.");

[Link]("Pehla object bana raha hun...");


MyClass obj1 = new MyClass();
[Link]("Doosra object bana raha hun...");
MyClass obj2 = new MyClass();

[Link]("Message: " + [Link]);


}
}

// Output (DHYAN SE DEKHO ORDER):


// Static Block Execute Ho Raha Hai! ← Constructor se PEHLE!
// x initialized: 42 ← Class load hote hi
// main() shuru ho gaya.
// Pehla object bana raha hun...
// Constructor call ho raha hai. ← Object bante waqt
// Doosra object bana raha hun...
// Constructor call ho raha hai. ← Doosra object
// Message: Hello from static block!

// Static Block SIRF EK BAAR chala — donon objects ke liye NAHI!

🎯 Bahut Important! Static Block ka output dekho — woh main() se bhi PEHLE print hua!

JVM ne socha: 'MyClass use ho rahi hai → pehle class load karo → static
block chalaao'
— yeh sab main() line execute hone se bhi PEHLE ho jaata hai.

Aur Static Block SIRF EK BAAR chala — chahe 2 objects bane ya 200 bane.

3.2 — Execution Order — Step by Step


Yeh Java mein ek bahut important concept hai — kaunsi cheez pehle execute hoti hai? Yeh order hamesha same
rehta hai:

Step Kya Hota Hai? Explanation Kitni Baar?


1️⃣ FIRST Static Variables Class ke static variables initialize hote JVM class load karte
Load hain waqt
2️⃣ Static Block static { ... } wala code run hota hai Sirf EK baar — class
SECOND Execute pehli baar load hone par
3️⃣ THIRD main() Method Program ka execution shuru hota hai Ya jo bhi first call hai us
class par
4️⃣ Constructor Call new ClassName() — object banta hai Jitni baar object bano,
FOURTH utni baar
5️⃣ FIFTH Instance Block { ... } wala non-static block (if any) Har baar object bante
waqt, constructor se
pehle

// Execution Order — Complete Proof with All Block Types


// Execution Order Proof — Sab ek saath dekhte hain
class Demo {

// Static variable — pehle initialize hoga


static int staticVar = initStatic();

// Instance variable
int instanceVar = initInstance();

// Static method for initialization


static int initStatic() {
[Link]("1️⃣ Static variable initialize ho raha hai.");
return 10;
}
int initInstance() {
[Link]("5️⃣ Instance variable initialize ho raha hai.");
return 20;
}

// Static Block
static {
[Link]("2️⃣ Static Block #1 execute ho raha hai. staticVar=" + staticVar);
}

// Instance Block (non-static) — constructor se pehle chalta hai


{
[Link]("4️⃣ Instance Block execute ho raha hai.");
}

// Constructor
Demo() {
[Link]("6️⃣ Constructor execute ho raha hai.");
}
}

public class Main {


public static void main(String[] args) {
[Link]("3️⃣ main() start ho gaya — pehla object bana raha hun.");
Demo d1 = new Demo();
[Link]("--- Doosra object ---");
Demo d2 = new Demo();
}
}

// Output:
// 1️⃣ Static variable initialize ho raha hai.
// 2️⃣ Static Block #1 execute ho raha hai. staticVar=10
// 3️⃣ main() start ho gaya — pehla object bana raha hun.
// 5️⃣ Instance variable initialize ho raha hai.
// 4️⃣ Instance Block execute ho raha hai.
// 6️⃣ Constructor execute ho raha hai.
// --- Doosra object ---
// 5️⃣ Instance variable initialize ho raha hai.
// 4️⃣ Instance Block execute ho raha hai.
// 6️⃣ Constructor execute ho raha hai.
// (Static wali steps dobara nahi huin — sirf ek baar!)

3.3 — Multiple Static Blocks — Ek Class mein Kaafi Saare


Java mein ek class mein MULTIPLE static blocks allowed hain. Woh sab UPAR SE NEECHE ki order mein execute
hote hain — ek ke baad ek. Yeh complex initialization ke liye useful hai.

// Multiple Static Blocks — Execution Order


// Multiple Static Blocks — Upar se neeche order mein
class MultiBlockDemo {

static int a;
static int b;
static int c;

// Static Block 1 — pehle chalega


static {
a = 100;
[Link]("Static Block 1: a = " + a);
}

// Static Block 2 — doosra chalega


static {
b = a * 2; // Block 1 ka a use kar sakte hain — already set hai!
[Link]("Static Block 2: b = " + b);
}

// Static Block 3 — teesra chalega


static {
c = a + b;
[Link]("Static Block 3: c = a + b = " + c);

// ── Complex initialization — e.g. database config load ──


[Link]("Final Setup Complete! a=" + a + " b=" + b + " c=" + c);
}
}

public class Main {


public static void main(String[] args) {
[Link]("main() start.");
MultiBlockDemo obj = new MultiBlockDemo();
[Link]("Values: " + MultiBlockDemo.a + ", " + MultiBlockDemo.b + ", " +
MultiBlockDemo.c);
}
}

// Output:
// Static Block 1: a = 100
// Static Block 2: b = 200
// Static Block 3: c = a + b = 300
// Final Setup Complete! a=100 b=200 c=300
// main() start.
// Values: 100, 200, 300

3.4 — Static Block ke Real-World Use Cases


Static Block sirf theory nahi hai — real projects mein iske bahut important uses hain. Sabse common use cases
dekhte hain:

// Static Block Real Use Cases — JDBC, Lookup Table, Properties


// ── Use Case 1: JDBC Driver Load (Classic Use!) ─────────────────────
class DatabaseConfig {
static String url;
static String username;
static String password;

static {
// JDBC driver load karo — yeh ek classic static block use case hai
try {
[Link]("[Link]");
[Link]("✅ MySQL Driver loaded successfully!");
} catch (ClassNotFoundException e) {
[Link]("❌ Driver nahi mila: " + [Link]());
}

// Config values set karo


url = "jdbc:mysql://localhost:3306/shopdb";
username = "root";
password = "password123";
[Link]("✅ Database config ready!");
}
}

// ── Use Case 2: Lookup Table / Cache Pre-load ─────────────────────────


class RomanNumerals {
// int → Roman numeral lookup table
static final int[] VALUES = new int[13];
static final String[] SYMBOLS = new String[13];

static {
// Static block mein lookup table initialize karo
int[] vals = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] syms = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
for (int i = 0; i < 13; i++) {
VALUES[i] = vals[i];
SYMBOLS[i] = syms[i];
}
[Link]("✅ Roman numeral lookup table ready!");
}

static String toRoman(int num) {


StringBuilder result = new StringBuilder();
for (int i = 0; i < [Link]; i++) {
while (num >= VALUES[i]) {
[Link](SYMBOLS[i]);
num -= VALUES[i];
}
}
return [Link]();
}
}

// ── Use Case 3: Properties File Load


─────────────────────────────────
class AppProperties {
static String appName;
static String environment;
static int serverPort;

static {
// Real project mein: Properties file se load karte hain
// Yahan simulate kar rahe hain
appName = [Link]("[Link]", "MyApp");
environment = [Link]("[Link]", "development");
serverPort = [Link]([Link]("[Link]","8080"));
[Link]("✅ App properties loaded!");
[Link](" App: " + appName + " | Env: " + environment + " | Port: " + serverPort);
}
}

public class Main {


public static void main(String[] args) {
[Link]("=== App Starting ===");

// Class mention hone par static blocks auto-run honge:


[Link]("DB URL: " + [Link]);
[Link]("\n=== Roman Numerals ===");
[Link]("2024 = " + [Link](2024));
[Link]("1999 = " + [Link](1999));
[Link]("42 = " + [Link](42));

[Link]("\n=== App Properties ===");


[Link]("Running on port: " + [Link]);
}
}

// Output:
// ✅ MySQL Driver loaded successfully! (ya ❌ agar driver nahi hai)
// ✅ Database config ready!
// DB URL: jdbc:mysql://localhost:3306/shopdb
// ✅ Roman numeral lookup table ready!
// 2024 = MMXXIV
// 1999 = MCMXCIX
// 42 = XLII
// ✅ App properties loaded!
// Running on port: 8080

3.5 — Static Block mein Exception Handling


Static block mein checked exceptions handle karna zaroori hota hai — kyunki agar static block mein koi uncaught
exception aaye, toh class hi load nahi ho paati — ExceptionInInitializerError aata hai!

// Static Block — Exception Handling Zaroori Hai!


// Static Block mein try-catch — Zaroori hai!
class SafeConfig {
static int configValue;
static boolean configLoaded = false;

static {
try {
// Risky operation — file read, DB connect, etc.
String val = [Link]("CONFIG_VALUE"); // null aa sakta hai

if (val != null) {
configValue = [Link](val);
} else {
configValue = 42; // Default value
[Link]("⚠️ Config not found — using default: " + configValue);
}
configLoaded = true;
[Link]("✅ Config loaded: " + configValue);

} catch (NumberFormatException e) {
configValue = 0;
configLoaded = false;
[Link]("❌ Config parse error: " + [Link]() + " — using 0");
} catch (Exception e) {
[Link]("❌ Unexpected error in static block: " + [Link]());
}
}
}

public class Main {


public static void main(String[] args) {
[Link]("Config Value: " + [Link]);
[Link]("Config Loaded: " + [Link]);
}
}

// ❌ Agar static block mein exception catch nahi ki:


class DangerousClass {
static {
int result = 10 / 0; // ArithmeticException!
// Catch nahi kiya → ExceptionInInitializerError → class load hi nahi hogi!
}
}
// DangerousClass use karne ki koshish → [Link]!

🏗️Complete Real-World Example — ATM System


Ab ek complete example dekhte hain — ek simple ATM System — jisme Static Variable aur Static Block dono use
hue hain:

// Complete ATM System — Static Variable + Static Block


//
════════════════════════════════════════════════════
══
// ATM System — Static Variable + Static Block
//
════════════════════════════════════════════════════
══

class ATM {

// ── STATIC variables — ATM ke shared properties ──


static String bankName;
static String branchCode;
static int totalATMs = 0;
static double totalCashInVault;
static int transactionCount = 0;
static final double MAX_WITHDRAWAL = 25000.0;
static final double MIN_WITHDRAWAL = 100.0;

// ── INSTANCE variables — har ATM machine ka apna data ──


int atmId;
String location;
double cashAvailable;
boolean isOnline;

// ── STATIC BLOCK — Bank system initialize karo ──


static {
[Link]("🏦 Bank System Initialize Ho Raha Hai...");
bankName = "Bihar Grameen Bank";
branchCode = "BGB-PTN-001";
totalCashInVault = 50_000_000.0; // 5 crore initial cash
[Link]("✅ Bank: " + bankName + " [" + branchCode + "]");
[Link]( "✅ Total Vault Cash: ₹%.0f%n", totalCashInVault);
[Link]("✅ System Ready! Machines connect kar sakte hain.");

[Link]("──────────────────────────────────────────
──");
}

// Constructor — har naye ATM machine ke liye


ATM(int atmId, String location, double cash) {
[Link] = atmId;
[Link] = location;
[Link] = cash;
[Link] = true;
totalATMs++;
[Link]("🏧 ATM #" + atmId + " online at: " + location +
" | Cash: ₹" + cash + " | Total ATMs: " + totalATMs);
}

// Withdraw method
boolean withdraw(String user, double amount) {
[Link]("\n👤 " + user + " → Withdraw Request: ₹" + amount);

if (!isOnline) {
[Link](" ❌ ATM offline hai!"); return false;
}
if (amount < MIN_WITHDRAWAL) {
[Link](" ❌ Minimum withdrawal ₹" + MIN_WITHDRAWAL); return false;
}
if (amount > MAX_WITHDRAWAL) {
[Link](" ❌ Maximum withdrawal ₹" + MAX_WITHDRAWAL); return false;
}
if (amount > cashAvailable) {
[Link](" ❌ ATM mein itna cash nahi!"); return false;
}

cashAvailable -= amount;
totalCashInVault -= amount; // Static — bank-wide cash update
transactionCount++; // Static — global counter
[Link](" ✅ ₹%.0f dispensed! ATM cash: ₹%.0f | Total txns: %d%n",
amount, cashAvailable, transactionCount);
return true;
}

static void bankStatus() {


[Link]("\n📊 BANK STATUS:");
[Link](" Bank: " + bankName);
[Link](" Total ATMs Online: " + totalATMs);
[Link]( " Total Vault Cash: ₹%.0f%n", totalCashInVault);
[Link](" Total Transactions: " + transactionCount);
}
}

public class Main {


public static void main(String[] args) {
[Link]("main() starting...");

// 3 ATM machines deploy karo


ATM atm1 = new ATM(1, "Patna Junction", 200000);
ATM atm2 = new ATM(2, "Gandhi Maidan", 150000);
ATM atm3 = new ATM(3, "Boring Road Market", 100000);

// Transactions
[Link]("Rakesh Kumar", 10000);
[Link]("Priya Sharma", 25000);
[Link]("Ajay Verma", 30000); // Limit exceed
[Link]("Sunita Devi", 50); // Below minimum
[Link]("Mohan Lal", 15000);

// Bank-wide status
[Link]();
}
}

// Output:
// 🏦 Bank System Initialize Ho Raha Hai...
// ✅ Bank: Bihar Grameen Bank [BGB-PTN-001]
// ✅ Total Vault Cash: ₹50000000
// ✅ System Ready!
// ────────────────────────────────────────────
// main() starting...
// 🏧 ATM #1 online at: Patna Junction | Cash: ₹200000.0 | Total ATMs: 1
// 🏧 ATM #2 online at: Gandhi Maidan | Cash: ₹150000.0 | Total ATMs: 2
// 🏧 ATM #3 online at: Boring Road | Cash: ₹100000.0 | Total ATMs: 3
// ✅ ₹10000 dispensed! ATM cash: ₹190000 | Total txns: 1
// ✅ ₹25000 dispensed! ATM cash: ₹125000 | Total txns: 2
// ❌ Maximum withdrawal ₹25000.0
// ❌ Minimum withdrawal ₹100.0
// ✅ ₹15000 dispensed! ATM cash: ₹110000 | Total txns: 3
// BANK STATUS: Total ATMs: 3 | Vault: ₹49950000 | Transactions: 3

📋 Quick Revision — Exam aur Interview ke Liye

Sabse Important Points — Pakka Yaad Karo


• static variable: class ki shared property — sab objects ek hi copy share karte hain
• Instance variable: har object ka apna — alag alag copy, Heap mein
• Memory: Static → Method Area | Instance → Heap Area
• Access: [Link] (best practice — object ki zaroorat nahi)
• Static Block: class load hote hi — SIRF EK BAAR — automatically execute
• Execution Order: Static vars → Static Block → main() → Instance Block → Constructor
• Multiple static blocks: allowed — upar se neeche order mein execute hote hain
• Exception in static block: pakdo! Nahi toh ExceptionInInitializerError → class load fail
• Static block use cases: JDBC driver load, lookup table init, config load, properties file
• Singleton pattern: static variable se ek hi object ensure karte hain — getInstance()

Topic Keyword / Syntax Hinglish Yaad-Sutra


static variable static int count = 0; Sab objects ki shared property — class ki apni
memory mein
Instance variable int id; String name; Har object ka apna — Heap mein alag alag
copy
Static access [Link] Object ki zaroorat nahi — class naam se
seedha
Static block static { ... } Class load hote hi chalta hai — sirf EK baar
Execution order static vars → static block → Static pehle, main baad mein — hamesha!
main()
Multiple static static{} static{} (allowed) Upar se neeche order mein execute hote hain
blocks
Static var use Counter, config, shared Jab sab objects mein ek hi value share ho
config
Instance var use name, age, id (per object) Jab har object ka apna alag data ho
Class loading JVM class ko pehli baar load Static sab class load hone par — object se
karta pehle
Memory area Method Area (Class Area) Static → Class Area | Instance → Heap Area
Java Programming Notes — Static Keyword Part 1 • Static Variable • Static Block • Execution Order | Hinglish
Edition 🇮🇳

You might also like