☕ Java — this Keyword

Complete Deep Revision Guide — Hinglish mein samjho, clearly padho | 4–5 Programs per topic with explanation

📚 Topics

📖

this Kya Hai? — Deep Explanation

class Student { String name; void show() { System.out.println(this); // current object ka reference } } Student s1 = new Student(); // s1 ek object Student s2 = new Student(); // s2 alag object s1.show(); // this = s1 ka reference s2.show(); // this = s2 ka reference
Memory mein this kaise kaam karta hai: HEAP Memory: ┌─────────────────┐ ┌─────────────────┐ │ Object s1 │ │ Object s2 │ │ address: 1000 │ │ address: 2000 │ │ name = "Rahul" │ │ name = "Priya" │ └─────────────────┘ └─────────────────┘ ↑ ↑ s1.show() mein s2.show() mein this = 1000 this = 2000 this = Jo bhi object ne method call kiya uska reference automatically!

4 Uses Overview

┌────────────────┬─────────────────────────────────────────┐ │ USE 1this.variable → ambiguity resolve │ │ USE 2this.method() → same class method call │ │ USE 3this() → same class constructor │ │ USE 4return this → method chaining │ └────────────────┴─────────────────────────────────────────┘
Rules Yaad Rakho: Static method mein this USE NAHI HOTA (Static ka koi object nahi hota!) this() HAMESHA constructor ki FIRST LINE this() aur super() ek saath nahi return this → method chaining enable karta hai
🔵

USE 1: this.variable — Variable Ambiguity Resolve 5 Programs

Problem: class Student { String name; ← instance variable void setName(String name) { ← parameter bhi "name"! name = name; ← GALAT! parameter khud ko assign instance variable nahi badla! } } Solution: void setName(String name) { this.name = name; ← this.name = instance variable } name = parameter
Memory mein kya hota hai: Stack (method ka): Heap (object ka): ┌──────────────┐ ┌──────────────────┐ │ name = "Raj" │ (parameter)│ this.name = ??? │ (instance var) └──────────────┘ └──────────────────┘ ↓ ↑ this.name = name → "Raj" yahan copy hoga

ThisVariable1.java
public class ThisVariable1 {

    // Instance variables
    String name;
    int    age;
    double salary;

    // Constructor - parameter naam same hai instance var se!
    ThisVariable1(String name, int age, double salary) {
        // this.name = instance variable (Heap)
        // name      = parameter (Stack)
        this.name   = name;    // ✅ sahi
        this.age    = age;
        this.salary = salary;
    }

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

    public static void main(String[] args) {

        ThisVariable1 e1 = new ThisVariable1("Rahul", 25, 50000);
        ThisVariable1 e2 = new ThisVariable1("Priya", 30, 75000);

        System.out.println("--- Employee 1 ---");
        e1.display();
        System.out.println("--- Employee 2 ---");
        e2.display();
    }
}
Output
--- Employee 1 --- Name: Rahul Age: 25 Salary: 50000.0 --- Employee 2 --- Name: Priya Age: 30 Salary: 75000.0
Short Explain: this.name = Heap mein object ka variable. name = Stack mein constructor ka parameter. Bina this ke Java parameter ko hi refer karta — instance variable kabhi update nahi hota!

ThisVariable2.java
public class ThisVariable2 {

    String name;
    int    marks;

    // WRONG behavior - bina this ke
    void setNameWrong(String name) {
        name = name;  // ❌ parameter khud ko assign kar raha hai!
                      // instance variable NAHI badla!
    }

    // RIGHT behavior - this ke saath
    void setNameRight(String name) {
        this.name = name;  // ✅ instance variable badla
    }

    void setMarks(int marks) {
        this.marks = marks;  // ✅ instance variable badla
    }

    void display(String label) {
        System.out.println(label +
            " → name='" + name + "' marks=" + marks);
    }

    public static void main(String[] args) {

        ThisVariable2 s = new ThisVariable2();
        s.display("Initial");   // null, 0

        s.setNameWrong("Rahul");
        s.display("After wrong set"); // still null!

        s.setNameRight("Rahul");
        s.setMarks(95);
        s.display("After right set"); // Rahul, 95
    }
}
Output
Initial → name='null' marks=0 After wrong set → name='null' marks=0 After right set → name='Rahul' marks=95
Short Explain: setNameWrong mein name = name → parameter khud ko assign kiya, instance variable null raha! setNameRight mein this.name = name → instance variable update hua. Yeh sabse common Java mistake hai!

ThisVariable3.java
public class ThisVariable3 {

    // Instance variables
    int    length;
    int    width;
    int    height;
    String color;
    double price;

    ThisVariable3(int length, int width,
                  int height, String color, double price) {
        this.length = length;
        this.width  = width;
        this.height = height;
        this.color  = color;
        this.price  = price;
    }

    // Method mein bhi this.variable use kar sakte hain
    void applyDiscount(double discount) {
        // discount = local parameter
        // this.price = instance variable
        double savedAmount = this.price * discount;
        this.price = this.price - savedAmount;
        System.out.printf("Discount %.0f%% applied! " +
            "Saved: Rs.%.2f | New Price: Rs.%.2f%n",
            discount * 100, savedAmount, this.price);
    }

    int getVolume() {
        return this.length * this.width * this.height;
    }

    void display() {
        System.out.println("Box: " + length + "x" + width + "x" + height
            + " | Color: " + color
            + " | Price: Rs." + price
            + " | Volume: " + getVolume());
    }

    public static void main(String[] args) {

        ThisVariable3 box = new ThisVariable3(
            10, 5, 3, "Blue", 2000.0);
        box.display();
        box.applyDiscount(0.20); // 20% discount
        box.display();
    }
}
Output
Box: 10x5x3 | Color: Blue | Price: Rs.2000.0 | Volume: 150 Discount 20% applied! Saved: Rs.400.00 | New Price: Rs.1600.00 Box: 10x5x3 | Color: Blue | Price: Rs.1600.0 | Volume: 150
Short Explain: Method ke andar bhi this.price se instance variable access kiya. discount parameter tha, this.price object ka actual price — dono alag scopes hain.

ThisVariable4.java
public class ThisVariable4 {

    // this.variable - shadowing concept
    String city    = "Default City";    // instance variable
    String country = "Default Country";

    void updateLocation(String city, String country) {
        // Local parameter "city" shadows instance "city"
        System.out.println("Parameter city:    " + city);        // local
        System.out.println("Instance city:     " + this.city);   // instance

        // Update instance variables
        this.city    = city;
        this.country = country;

        System.out.println("After update:");
        System.out.println("this.city    = " + this.city);
        System.out.println("this.country = " + this.country);
    }

    void compareScope(int value) {
        int result = value * 2;       // local variable
        System.out.println("\nLocal result:    " + result);
        System.out.println("Instance value used: " + value);
    }

    public static void main(String[] args) {

        ThisVariable4 obj = new ThisVariable4();
        System.out.println("Before:");
        System.out.println("city = " + obj.city);

        obj.updateLocation("Mumbai", "India");

        System.out.println("\nFinal:");
        System.out.println("city    = " + obj.city);
        System.out.println("country = " + obj.country);

        obj.compareScope(50);
    }
}
Output
Before: city = Default City Parameter city: Mumbai Instance city: Default City After update: this.city = Mumbai this.country = India Final: city = Mumbai country = India Local result: 100 Instance value used: 50
Short Explain: Variable Shadowing — parameter ka naam instance variable ke naam se same hone par parameter "shadow" karta hai. this.city se clearly instance variable access hoti hai, nahi toh sirf parameter milega.

ThisVariable5.java
public class ThisVariable5 {

    // this in static - ERROR demonstration
    static String appName = "MyApp";
    String userName;
    int    userId;

    ThisVariable5(String userName, int userId) {
        this.userName = userName;  // ✅ instance method mein OK
        this.userId   = userId;
    }

    // ✅ Instance method - this use kar sakte hain
    void instanceMethod() {
        System.out.println("this.userName = " + this.userName);
        System.out.println("this.userId   = " + this.userId);
        System.out.println("appName       = " + appName);
    }

    // ✅ Static method - this USE NAHI HOTA!
    static void staticMethod() {
        System.out.println("appName = " + appName);   // ✅ static var
        // System.out.println(this.userName); // ❌ ERROR!
        // "non-static variable userName cannot be referenced
        //  from a static context"
        System.out.println("Static method: no 'this' here!");
    }

    public static void main(String[] args) {

        ThisVariable5 u = new ThisVariable5("Rahul", 101);

        System.out.println("--- Instance Method ---");
        u.instanceMethod();

        System.out.println("\n--- Static Method ---");
        ThisVariable5.staticMethod();
    }
}
Output
--- Instance Method --- this.userName = Rahul this.userId = 101 appName = MyApp --- Static Method --- appName = MyApp Static method: no 'this' here!
Short Explain: Static method mein this nahi hota — kyunki static method bina object ke call ho sakta hai. this = current object ka reference, object hi nahi toh this kahan se aayega?
🟢

USE 2: this.method() — Current Class Method Call 4 Programs

class Calculator { void add(int a, int b) { int result = a + b; this.printResult(result); // same class ka method call } void printResult(int r) { System.out.println("Result: " + r); } }
Kab zaroori hai: Clarity ke liye - "yeh method is class ka hai" Overriding context mein (inheritance mein important) Code readability improve karna Technically required nahi - direct naam se bhi call kar sakte

ThisMethod1.java
public class ThisMethod1 {

    String studentName;
    int[]  marks;

    ThisMethod1(String name, int[] marks) {
        this.studentName = name;
        this.marks = marks;
    }

    // Helper methods
    int calculateTotal() {
        int total = 0;
        for (int m : marks) total += m;
        return total;
    }

    double calculateAverage() {
        return (double) this.calculateTotal() / marks.length;
        //              ↑ this se same class ka method call
    }

    String getGrade() {
        double avg = this.calculateAverage(); // this se call
        if (avg >= 90) return "A+";
        else if (avg >= 75) return "A";
        else if (avg >= 60) return "B";
        else if (avg >= 35) return "C";
        else return "F";
    }

    void generateReport() {
        System.out.println("=== Report Card ===");
        System.out.println("Student:  " + this.studentName);
        System.out.println("Total:    " + this.calculateTotal());
        System.out.printf ("Average:  %.2f%n", this.calculateAverage());
        System.out.println("Grade:    " + this.getGrade());
    }

    public static void main(String[] args) {

        ThisMethod1 s1 = new ThisMethod1("Rahul",
            new int[]{85, 90, 78, 92, 88});
        ThisMethod1 s2 = new ThisMethod1("Priya",
            new int[]{95, 98, 92, 96, 99});

        s1.generateReport();
        System.out.println();
        s2.generateReport();
    }
}
Output
=== Report Card === Student: Rahul Total: 433 Average: 86.60 Grade: A === Report Card === Student: Priya Total: 480 Average: 96.00 Grade: A+
Short Explain: this.calculateTotal(), this.calculateAverage() — same class ke methods this se call kiye. generateReport() ek method hai jo doosre methods ko internally chain karta hai.

ThisMethod2.java
public class ThisMethod2 {

    double accountBalance;
    String ownerName;
    int    transactionCount;

    ThisMethod2(String owner, double initialBalance) {
        this.ownerName        = owner;
        this.accountBalance   = initialBalance;
        this.transactionCount = 0;
    }

    // Helper method
    boolean hasSufficientBalance(double amount) {
        return this.accountBalance >= amount;
    }

    void recordTransaction(String type, double amount) {
        this.transactionCount++;
        System.out.printf("Transaction #%d | %-10s | Rs.%-10.2f" +
            " | Balance: Rs.%.2f%n",
            transactionCount, type, amount, accountBalance);
    }

    void deposit(double amount) {
        if (amount > 0) {
            this.accountBalance += amount;
            this.recordTransaction("DEPOSIT", amount); // this se call
        } else {
            System.out.println("Invalid deposit amount!");
        }
    }

    void withdraw(double amount) {
        if (this.hasSufficientBalance(amount)) { // this se check
            this.accountBalance -= amount;
            this.recordTransaction("WITHDRAW", amount);
        } else {
            System.out.println("Insufficient balance! " +
                "Available: Rs." + this.accountBalance);
        }
    }

    void showBalance() {
        System.out.println("\n" + ownerName +
            "'s Balance: Rs." + accountBalance);
        System.out.println("Total Transactions: " + transactionCount);
    }

    public static void main(String[] args) {

        ThisMethod2 acc = new ThisMethod2("Rahul", 10000.0);
        acc.showBalance();
        System.out.println();

        acc.deposit(5000);
        acc.deposit(3000);
        acc.withdraw(2000);
        acc.withdraw(20000); // fail
        acc.withdraw(8000);

        acc.showBalance();
    }
}
Output
Rahul's Balance: Rs.10000.0 Total Transactions: 0 Transaction #1 | DEPOSIT | Rs.5000.00 | Balance: Rs.15000.00 Transaction #2 | DEPOSIT | Rs.3000.00 | Balance: Rs.18000.00 Transaction #3 | WITHDRAW | Rs.2000.00 | Balance: Rs.16000.00 Insufficient balance! Available: Rs.16000.0 Transaction #4 | WITHDRAW | Rs.8000.00 | Balance: Rs.8000.00 Rahul's Balance: Rs.8000.0 Total Transactions: 4
Short Explain: this.hasSufficientBalance() aur this.recordTransaction() — main methods ne helper methods ko this se internally call kiya. Bank account logic clearly organized hai!

ThisMethod3.java
public class ThisMethod3 {

    String  title;
    boolean isOn;
    int     brightness;
    String  color;

    ThisMethod3(String title) {
        this.title      = title;
        this.isOn       = false;
        this.brightness = 50;
        this.color      = "White";
    }

    void validateBrightness(int b) {
        if (b < 0 || b > 100) {
            throw new IllegalArgumentException(
                "Brightness must be 0-100! Got: " + b);
        }
    }

    void logChange(String change) {
        System.out.println("[" + title + "] " + change);
    }

    void turnOn() {
        this.isOn = true;
        this.logChange("Turned ON"); // this se call
    }

    void turnOff() {
        this.isOn = false;
        this.logChange("Turned OFF");
    }

    void setBrightness(int brightness) {
        this.validateBrightness(brightness); // this se validate
        this.brightness = brightness;
        this.logChange("Brightness set to " + brightness);
    }

    void setColor(String color) {
        this.color = color;
        this.logChange("Color changed to " + color);
    }

    void showStatus() {
        System.out.println("\n=== " + title + " Status ===");
        System.out.println("Power:      " + (isOn ? "ON" : "OFF"));
        System.out.println("Brightness: " + brightness + "%");
        System.out.println("Color:      " + color);
    }

    public static void main(String[] args) {

        ThisMethod3 light = new ThisMethod3("Living Room Light");

        light.turnOn();
        light.setBrightness(80);
        light.setColor("Warm Yellow");
        light.showStatus();

        System.out.println();
        light.setBrightness(30);
        light.turnOff();
        light.showStatus();
    }
}
Output
[Living Room Light] Turned ON [Living Room Light] Brightness set to 80 [Living Room Light] Color changed to Warm Yellow === Living Room Light Status === Power: ON Brightness: 80% Color: Warm Yellow [Living Room Light] Brightness set to 30 [Living Room Light] Turned OFF === Living Room Light Status === Power: OFF Brightness: 30% Color: Warm Yellow
Short Explain: Smart Light system — setBrightness() ne pehle this.validateBrightness() call ki, phir this.logChange(). Helper methods ko this se call karke code modular aur clean hai.

ThisMethod4.java
public class ThisMethod4 {

    // this.method() - validation chain example
    String  username;
    String  email;
    String  password;
    boolean isValid;

    ThisMethod4(String username, String email, String password) {
        this.username = username;
        this.email    = email;
        this.password = password;
        this.isValid  = this.validateAll(); // this se call
    }

    boolean validateUsername() {
        boolean ok = username != null && username.length() >= 3;
        System.out.println("Username valid: " + ok);
        return ok;
    }

    boolean validateEmail() {
        boolean ok = email != null && email.contains("@")
                     && email.contains(".");
        System.out.println("Email valid:    " + ok);
        return ok;
    }

    boolean validatePassword() {
        boolean ok = password != null && password.length() >= 8;
        System.out.println("Password valid: " + ok);
        return ok;
    }

    // Master validator - this se sab call karta hai
    boolean validateAll() {
        System.out.println("--- Validating: " + username + " ---");
        return this.validateUsername()  // this se call
            && this.validateEmail()     // this se call
            && this.validatePassword(); // this se call
    }

    void showResult() {
        System.out.println("Registration: " +
            (isValid ? "✅ SUCCESS" : "❌ FAILED"));
        System.out.println();
    }

    public static void main(String[] args) {

        ThisMethod4 u1 = new ThisMethod4(
            "rahul_dev", "rahul@gmail.com", "SecurePass123");
        u1.showResult();

        ThisMethod4 u2 = new ThisMethod4(
            "ab", "notanemail", "short");
        u2.showResult();
    }
}
Output
--- Validating: rahul_dev --- Username valid: true Email valid: true Password valid: true Registration: ✅ SUCCESS --- Validating: ab --- Username valid: false Registration: ❌ FAILED
Short Explain: validateAll() ne 3 alag validators ko this se call kiya — && (short-circuit) ki wajah se ab ke liye sirf username fail hone par aage check hi nahi hua. Clean validation chain!
🟡

USE 3: this() — Same Class Constructor Call 4 Programs

Constructor Chaining with this(): class Phone { Phone() { this("Unknown", 0); ← 2-param constructor call karo // FIRST LINE hona ZAROORI! } Phone(String brand, int price) { this.brand = brand; this.price = price; } }
Execution Flow: Phone() called ↓ this("Unknown", 0) → Phone(String, int) called ↓ brand = "Unknown" price = 0 ↓ wapas Phone() mein (baaki code agar hai)
Rules: HAMESHA FIRST statement honi chahiye Code reuse - DRY principle Ek main constructor mein sab logic Circular this() chain nahi kar sakte this() ke pehle koi statement nahi this() aur super() ek saath nahi

ThisConstructor1.java
public class ThisConstructor1 {

    String name;
    int    age;
    String city;
    String country;
    String role;

    // MASTER constructor - actual initialization yahan
    ThisConstructor1(String name, int age,
                     String city, String country, String role) {
        this.name    = name;
        this.age     = age;
        this.city    = city;
        this.country = country;
        this.role    = role;
        System.out.println("MASTER constructor: all 5 params");
    }

    // 4 params - default role = "User"
    ThisConstructor1(String name, int age,
                     String city, String country) {
        this(name, age, city, country, "User"); // FIRST LINE!
        System.out.println("4-param constructor");
    }

    // 3 params - default country = "India"
    ThisConstructor1(String name, int age, String city) {
        this(name, age, city, "India"); // FIRST LINE!
        System.out.println("3-param constructor");
    }

    // 2 params - default city = "Delhi"
    ThisConstructor1(String name, int age) {
        this(name, age, "Delhi"); // FIRST LINE!
        System.out.println("2-param constructor");
    }

    // 1 param - default age = 18
    ThisConstructor1(String name) {
        this(name, 18); // FIRST LINE!
        System.out.println("1-param constructor");
    }

    void display() {
        System.out.println("→ " + name + " | " + age +
            " | " + city + " | " + country + " | " + role);
    }

    public static void main(String[] args) {

        System.out.println("=== 1 param ===");
        ThisConstructor1 p1 = new ThisConstructor1("Rahul");
        p1.display();

        System.out.println("\n=== 3 params ===");
        ThisConstructor1 p2 = new ThisConstructor1("Priya", 25, "Mumbai");
        p2.display();

        System.out.println("\n=== All 5 params ===");
        ThisConstructor1 p3 = new ThisConstructor1(
            "Bob", 30, "London", "UK", "Admin");
        p3.display();
    }
}
Output
=== 1 param === MASTER constructor: all 5 params 4-param constructor 3-param constructor 2-param constructor 1-param constructor → Rahul | 18 | Delhi | India | User === 3 params === MASTER constructor: all 5 params 4-param constructor 3-param constructor → Priya | 25 | Mumbai | India | User === All 5 params === MASTER constructor: all 5 params → Bob | 30 | London | UK | Admin
Short Explain: Chain 1→2→3→4→MASTER — MASTER pehle execute hota hai (bottom-up execution), phir wapas aate hain (print reverse order mein). Yahi constructor chaining ka flow hai!

ThisConstructor2.java
public class ThisConstructor2 {

    String  productName;
    String  category;
    double  price;
    int     stock;
    double  discount;
    boolean available;

    // MASTER constructor
    ThisConstructor2(String productName, String category,
                     double price, int stock, double discount) {
        this.productName = productName;
        this.category    = category;
        this.price       = price;
        this.stock       = stock;
        this.discount    = discount;
        this.available   = stock > 0;
    }

    // Without discount - default 0%
    ThisConstructor2(String productName, String category,
                     double price, int stock) {
        this(productName, category, price, stock, 0.0);
    }

    // Minimum info - default stock=10, discount=0
    ThisConstructor2(String productName,
                     String category, double price) {
        this(productName, category, price, 10);
    }

    // Just name and price
    ThisConstructor2(String productName, double price) {
        this(productName, "General", price);
    }

    double getFinalPrice() {
        return price - (price * discount / 100);
    }

    void display() {
        System.out.printf(
            "%-15s | %-12s | MRP:Rs.%-8.2f | " +
            "Disc:%.0f%% | Final:Rs.%-8.2f | Stock:%-4d | %s%n",
            productName, category, price,
            discount, getFinalPrice(),
            stock, available ? "✅" : "❌");
    }

    public static void main(String[] args) {

        System.out.println("=== Product Catalog ===\n");

        ThisConstructor2 p1 = new ThisConstructor2(
            "Laptop", "Electronics", 65000, 15, 10.0);
        ThisConstructor2 p2 = new ThisConstructor2(
            "Phone", "Electronics", 25000, 50);
        ThisConstructor2 p3 = new ThisConstructor2(
            "Headphones", "Audio", 3500);
        ThisConstructor2 p4 = new ThisConstructor2(
            "Pen Drive", 799.0);

        p1.display();
        p2.display();
        p3.display();
        p4.display();
    }
}
Output
=== Product Catalog === Laptop | Electronics | MRP:Rs.65000.00 | Disc:10% | Final:Rs.58500.00 | Stock:15 | ✅ Phone | Electronics | MRP:Rs.25000.00 | Disc:0% | Final:Rs.25000.00 | Stock:50 | ✅ Headphones | Audio | MRP:Rs.3500.00 | Disc:0% | Final:Rs.3500.00 | Stock:10 | ✅ Pen Drive | General | MRP:Rs.799.00 | Disc:0% | Final:Rs.799.00 | Stock:10 | ✅
Short Explain: 4 constructors — alag-alag levels of detail. Sirf naam+price diya toh defaults chain se automatically set ho gaye. DRY principle — sab logic sirf MASTER constructor mein!

ThisConstructor3.java
public class ThisConstructor3 {

    // this() FIRST LINE rule demonstration
    int    x, y, z;
    String label;

    // MASTER
    ThisConstructor3(String label, int x, int y, int z) {
        this.label = label;
        this.x = x;
        this.y = y;
        this.z = z;
    }

    // ✅ CORRECT - this() first line
    ThisConstructor3(int x, int y, int z) {
        this("Point", x, y, z);  // ✅ FIRST LINE
        System.out.println("3D point created");
    }

    // ✅ CORRECT - this() first line
    ThisConstructor3(int x, int y) {
        this(x, y, 0);           // ✅ FIRST LINE
        System.out.println("2D point created (z=0)");
    }

    // ❌ WRONG - yeh compile error dega
    // ThisConstructor3(int x) {
    //     System.out.println("Before this"); // ❌ ERROR!
    //     this(x, 0, 0);  // this() must be FIRST!
    // }

    void display() {
        System.out.println(label + "(" + x + ", " + y + ", " + z + ")");
    }

    public static void main(String[] args) {

        System.out.println("=== 2D Point ===");
        ThisConstructor3 p2d = new ThisConstructor3(5, 10);
        p2d.display();

        System.out.println("\n=== 3D Point ===");
        ThisConstructor3 p3d = new ThisConstructor3(5, 10, 15);
        p3d.display();

        System.out.println("\n=== Named Point ===");
        ThisConstructor3 pNamed = new ThisConstructor3(
            "Origin", 0, 0, 0);
        pNamed.display();
    }
}
Output
=== 2D Point === 3D point created 2D point created (z=0) Point(5, 10, 0) === 3D Point === 3D point created Point(5, 10, 15) === Named Point === Origin(0, 0, 0)
Short Explain: this() ke baad code likh sakte hain — error sirf tab aata hai jab this() first line na ho. 2D point banate waqt 2D→3D→MASTER chain chali — z=0 automatically set hua.

ThisConstructor4.java
public class ThisConstructor4 {

    // Real world: DB Configuration object
    String  host;
    int     port;
    String  database;
    String  username;
    String  password;
    int     timeout;
    boolean ssl;

    // MASTER - full configuration
    ThisConstructor4(String host, int port, String database,
                     String username, String password,
                     int timeout, boolean ssl) {
        this.host     = host;
        this.port     = port;
        this.database = database;
        this.username = username;
        this.password = password;
        this.timeout  = timeout;
        this.ssl      = ssl;
    }

    // Without SSL - default false
    ThisConstructor4(String host, int port, String database,
                     String username, String password, int timeout) {
        this(host, port, database, username, password, timeout, false);
    }

    // Default timeout = 30 seconds
    ThisConstructor4(String host, int port, String database,
                     String username, String password) {
        this(host, port, database, username, password, 30);
    }

    // Default port = 3306 (MySQL default)
    ThisConstructor4(String host, String database,
                     String username, String password) {
        this(host, 3306, database, username, password);
    }

    // Local development shortcut
    ThisConstructor4(String database) {
        this("localhost", database, "root", "");
    }

    void display() {
        System.out.println("Host:     " + host + ":" + port);
        System.out.println("Database: " + database);
        System.out.println("User:     " + username);
        System.out.println("Timeout:  " + timeout + "s");
        System.out.println("SSL:      " + ssl);
        System.out.println("---");
    }

    public static void main(String[] args) {

        System.out.println("=== DB Configurations ===\n");

        // Local dev - sirf database naam diya!
        ThisConstructor4 local = new ThisConstructor4("myapp_db");
        local.display();

        // Production - full config
        ThisConstructor4 prod = new ThisConstructor4(
            "prod-server.com", 5432,
            "proddb", "admin", "SecurePass123", 60, true);
        prod.display();
    }
}
Output
=== DB Configurations === Host: localhost:3306 Database: myapp_db User: root Timeout: 30s SSL: false --- Host: prod-server.com:5432 Database: proddb User: admin Timeout: 60s SSL: true ---
Short Explain: Real-world DB config! Sirf "myapp_db" dene par automatically localhost:3306, root, timeout=30, ssl=false set ho gaya — yahi constructor chaining ki taaqat hai!
🔴

USE 4: return this — Method Chaining 4 Programs

return this = Current object wapas karo Method Chaining: obj.method1().method2().method3(); ↓ ↓ ↓ returns returns returns this this this ↓ ↓ same same object object
Bina return this: Pizza p = new Pizza(); p.setSize("Large"); // 4 alag lines p.setCrust("Thin"); p.setTopping("Cheese"); p.order(); return this ke saath: new Pizza() .setSize("Large") .setCrust("Thin") .setTopping("Cheese") .order(); // ek clean chain! Builder Pattern: Jab object mein bahut saare optional fields hon toh return this se Builder Pattern banate hain

ReturnThis1.java
public class ReturnThis1 {

    int value = 0;

    // return this - same object wapas
    ReturnThis1 add(int n) {
        this.value += n;
        return this;  // ← same object wapas
    }

    ReturnThis1 multiply(int n) {
        this.value *= n;
        return this;
    }

    ReturnThis1 subtract(int n) {
        this.value -= n;
        return this;
    }

    ReturnThis1 reset() {
        this.value = 0;
        return this;
    }

    void show() {
        System.out.println("Value = " + value);
    }

    public static void main(String[] args) {

        ReturnThis1 calc = new ReturnThis1();

        // Without method chaining (old way)
        System.out.println("--- Without Chaining ---");
        calc.add(10);
        calc.multiply(3);
        calc.subtract(5);
        calc.show();   // (0+10)*3-5 = 25

        // With method chaining (clean way)
        System.out.println("--- With Chaining ---");
        calc.reset()
            .add(10)
            .multiply(3)
            .subtract(5)
            .show();

        // Different chains
        System.out.println("--- Complex Chain ---");
        calc.reset()
            .add(100)
            .add(50)
            .subtract(30)
            .multiply(2)
            .show(); // (100+50-30)*2 = 240
    }
}
Output
--- Without Chaining --- Value = 25 --- With Chaining --- Value = 25 --- Complex Chain --- Value = 240
Short Explain: return this → same object wapas milta hai → usi object par agle method call kar sakte hain → Method Chaining! calc.reset().add(10) mein reset() ne calc wapas diya, usi par add(10) chala.

ReturnThis2.java
public class ReturnThis2 {

    // Builder Pattern - Real World Use
    String firstName;
    String lastName;
    int    age;
    String email;
    String phone;
    String address;
    String occupation;

    ReturnThis2() { }

    // Setter methods - sab return this!
    ReturnThis2 setFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }
    ReturnThis2 setLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }
    ReturnThis2 setAge(int age) {
        this.age = age;
        return this;
    }
    ReturnThis2 setEmail(String email) {
        this.email = email;
        return this;
    }
    ReturnThis2 setPhone(String phone) {
        this.phone = phone;
        return this;
    }
    ReturnThis2 setAddress(String address) {
        this.address = address;
        return this;
    }
    ReturnThis2 setOccupation(String occupation) {
        this.occupation = occupation;
        return this;
    }

    void displayProfile() {
        System.out.println("=== User Profile ===");
        System.out.println("Name:       " + firstName + " " + lastName);
        System.out.println("Age:        " + age);
        System.out.println("Email:      " + email);
        System.out.println("Phone:      " + phone);
        System.out.println("Address:    " + address);
        System.out.println("Occupation: " + occupation);
    }

    public static void main(String[] args) {

        // Builder Pattern with method chaining!
        ReturnThis2 user1 = new ReturnThis2()
            .setFirstName("Rahul")
            .setLastName("Sharma")
            .setAge(28)
            .setEmail("rahul@gmail.com")
            .setPhone("9876543210")
            .setAddress("Delhi, India")
            .setOccupation("Software Engineer");

        user1.displayProfile();
        System.out.println();

        // Partial profile - sirf zaroori fields
        ReturnThis2 user2 = new ReturnThis2()
            .setFirstName("Priya")
            .setLastName("Singh")
            .setAge(25)
            .setEmail("priya@email.com");

        user2.displayProfile();
    }
}
Output
=== User Profile === Name: Rahul Sharma Age: 28 Email: rahul@gmail.com Phone: 9876543210 Address: Delhi, India Occupation: Software Engineer === User Profile === Name: Priya Singh Age: 25 Email: priya@email.com Phone: null Address: null Occupation: null
Short Explain: Builder Pattern — bahut saare optional fields ko ek chain mein set karo. Sirf jo chahiye woh set karo, baaki null rahenge. Real Android, Spring Framework sab yahi pattern use karte hain!

ReturnThis3.java
public class ReturnThis3 {

    // SQL Query Builder simulation
    String        tableName;
    String        columns;
    String        whereClause;
    String        orderBy;
    int           limitCount;
    StringBuilder query;

    ReturnThis3() {
        this.columns    = "*";
        this.limitCount = -1;
        this.query      = new StringBuilder();
    }

    ReturnThis3 from(String tableName) {
        this.tableName = tableName;
        return this;
    }
    ReturnThis3 select(String columns) {
        this.columns = columns;
        return this;
    }
    ReturnThis3 where(String condition) {
        this.whereClause = condition;
        return this;
    }
    ReturnThis3 orderBy(String column) {
        this.orderBy = column;
        return this;
    }
    ReturnThis3 limit(int count) {
        this.limitCount = count;
        return this;
    }

    String build() {
        query = new StringBuilder();
        query.append("SELECT ").append(columns);
        query.append(" FROM ").append(tableName);
        if (whereClause != null)
            query.append(" WHERE ").append(whereClause);
        if (orderBy != null)
            query.append(" ORDER BY ").append(orderBy);
        if (limitCount > 0)
            query.append(" LIMIT ").append(limitCount);
        return query.toString();
    }

    public static void main(String[] args) {

        String q1 = new ReturnThis3()
            .from("users")
            .build();
        System.out.println("Q1: " + q1);

        String q2 = new ReturnThis3()
            .select("name, email, age")
            .from("users")
            .where("age > 18")
            .orderBy("name")
            .limit(10)
            .build();
        System.out.println("Q2: " + q2);

        String q3 = new ReturnThis3()
            .select("product, price, stock")
            .from("inventory")
            .where("price < 1000 AND stock > 0")
            .orderBy("price")
            .limit(5)
            .build();
        System.out.println("Q3: " + q3);
    }
}
Output
Q1: SELECT * FROM users Q2: SELECT name, email, age FROM users WHERE age > 18 ORDER BY name LIMIT 10 Q3: SELECT product, price, stock FROM inventory WHERE price < 1000 AND stock > 0 ORDER BY price LIMIT 5
Short Explain: SQL Query Builder — return this se har method same object deta hai aur agle method par jump hota hai. Ek readable chain se puri query build ho jaati hai! Yahi real ORM frameworks (Hibernate, JPA) karte hain.

ReturnThis4.java — All 4 Uses Combined!
public class ReturnThis4 {

    // Complete example - all 4 this uses together!
    String name;
    int    health;
    int    attack;
    int    defense;
    int    level;

    // USE 3: this() - constructor chaining
    ReturnThis4(String name) {
        this(name, 100, 10, 5); // FIRST LINE!
        System.out.println("Character created: " + name);
    }

    // MASTER constructor
    ReturnThis4(String name, int health, int attack, int defense) {
        // USE 1: this.variable - ambiguity resolve
        this.name    = name;
        this.health  = health;
        this.attack  = attack;
        this.defense = defense;
        this.level   = 1;
    }

    // USE 2: this.method() - same class method call
    void levelUp() {
        this.level++;
        this.upgradeStats(); // this se same class method call
        System.out.println(name + " leveled up to " + level + "!");
    }

    void upgradeStats() {
        this.health  += 20;
        this.attack  += 5;
        this.defense += 3;
    }

    // USE 4: return this - method chaining
    ReturnThis4 equipWeapon(String weapon) {
        System.out.println(name + " equipped: " + weapon);
        this.attack += 15;
        return this;
    }

    ReturnThis4 equipArmor(String armor) {
        System.out.println(name + " equipped: " + armor);
        this.defense += 10;
        return this;
    }

    ReturnThis4 heal(int amount) {
        this.health += amount;
        System.out.println(name + " healed +" + amount + "HP");
        return this;
    }

    void showStats() {
        System.out.println("\n=== " + name + " Stats ===");
        System.out.println("Level:   " + level);
        System.out.println("Health:  " + health);
        System.out.println("Attack:  " + attack);
        System.out.println("Defense: " + defense);
    }

    public static void main(String[] args) {

        // USE 3: this() - 1-param constructor chains to master
        ReturnThis4 hero = new ReturnThis4("Arjun");
        hero.showStats();

        System.out.println();
        hero.levelUp(); // USE 2: calls upgradeStats() internally
        hero.levelUp();

        // USE 4: return this - method chaining
        System.out.println();
        hero.equipWeapon("Divine Bow")
            .equipArmor("Golden Shield")
            .heal(50);

        hero.showStats();
    }
}
Output
Character created: Arjun === Arjun Stats === Level: 1 Health: 100 Attack: 10 Defense: 5 Arjun leveled up to 2! Arjun leveled up to 3! Arjun equipped: Divine Bow Arjun equipped: Golden Shield Arjun healed +50HP === Arjun Stats === Level: 3 Health: 190 Attack: 45 Defense: 31
Short Explain: Ek program mein charo this uses — this.variable (ambiguity), this.method() (internal call), this() (constructor chain), return this (method chaining). Yeh real game character system jaisa design hai!
📋

Complete Revision Summary

┌──────────────────┬────────────────────────────────────────────┐ │ this KA USE │ EXPLANATION │ ├──────────────────┼────────────────────────────────────────────┤ │ this.variable │ Parameter aur instance variable ka naam │ │ │ same ho toh ambiguity solve karo │ │ │ this.name = instance, name = parameter │ ├──────────────────┼────────────────────────────────────────────┤ │ this.method() │ Same class ka method explicitly call karo │ │ │ Clarity + readability ke liye │ │ │ Technically optional par good practice │ ├──────────────────┼────────────────────────────────────────────┤ │ this() │ Same class ka DOOSRA constructor call karo │ │ │ HAMESHA FIRST LINE honi chahiye │ │ │ Code reuse - DRY principle │ │ │ Circular chain nahi kar sakte │ ├──────────────────┼────────────────────────────────────────────┤ │ return this │ Current object wapas karo │ │ │ Method Chaining enable karta hai │ │ │ Builder Pattern mein use hota hai │ └──────────────────┴────────────────────────────────────────────┘

⭐ Rules — Exam Sheet

Static method mein this NAHI hota → Static ka koi object nahi, this kahan se aayega? this() HAMESHA constructor ki FIRST LINE → Pehle koi statement nahi likh sakte this() aur super() ek constructor mein saath nahi → Sirf ek allowed - ya this() ya super() return this → same object return → method chaining this.variable → instance var access (parameter shadow kare toh) this refer karta hai → object jo abhi method call kar raha hai

⭐ Interview Questions

Q: this keyword kya hai Java mein?
A: this = current object ka reference. Jo object method call kar raha hai, uska address this mein hota hai.
Q: this aur this() mein difference?
A: this → current object ka reference (variable/method access) this() → same class ka constructor call (constructor chaining)
Q: Static method mein this kyun nahi hota?
A: Static method bina object ke call ho sakta hai. this = object ka reference, object hi nahi toh this kahan se aayega!
Q: return this kab use karte hain?
A: Method Chaining aur Builder Pattern mein. obj.setA().setB().setC() — har method same object wapas deta hai.
Q: this() FIRST LINE kyun honi chahiye?
A: Java ka rule hai — constructor call hone se pehle koi initialization nahi ho sakti. Compiler enforce karta hai yeh rule.
Q: this.variable kab zaroori hai?
A: Jab parameter aur instance variable ka naam same ho. this.name = name; → this.name (Heap), name (Stack parameter)

⚠️ Common Mistakes Table

MistakeWrong ❌Right ✅
Bina this variable setname = name;this.name = name;
this() not first linex=5; this(10);this(10); x=5;
this in staticstatic void m(){ this.x; }Remove static / use object
Circular thisA()→B()→A()One direction chain only
Both this + superthis(1); super();Choose one only
Golden Rule: File name = Class name exactly. Jaise class ReturnThis1 hai toh file ReturnThis1.java hogi!