this KeywordComplete Deep Revision Guide — Hinglish mein samjho, clearly padho | 4–5 Programs per topic with explanation
this.variable — Variable Ambiguity Resolve 5 Programspublic 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(); } }
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!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 } }
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!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(); } }
this.price se instance variable access kiya. discount parameter tha, this.price object ka actual price — dono alag scopes hain.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); } }
this.city se clearly instance variable access hoti hai, nahi toh sirf parameter milega.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(); } }
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?this.method() — Current Class Method Call 4 Programspublic 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(); } }
this.calculateTotal(), this.calculateAverage() — same class ke methods this se call kiye. generateReport() ek method hai jo doosre methods ko internally chain karta hai.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(); } }
this.hasSufficientBalance() aur this.recordTransaction() — main methods ne helper methods ko this se internally call kiya. Bank account logic clearly organized hai!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(); } }
setBrightness() ne pehle this.validateBrightness() call ki, phir this.logChange(). Helper methods ko this se call karke code modular aur clean hai.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(); } }
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!this() — Same Class Constructor Call 4 Programspublic 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(); } }
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!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(); } }
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(); } }
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.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(); } }
"myapp_db" dene par automatically localhost:3306, root, timeout=30, ssl=false set ho gaya — yahi constructor chaining ki taaqat hai!return this — Method Chaining 4 Programspublic 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 } }
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.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(); } }
null rahenge. Real Android, Spring Framework sab yahi pattern use karte hain!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); } }
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.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(); } }
this uses — this.variable (ambiguity), this.method() (internal call), this() (constructor chain), return this (method chaining). Yeh real game character system jaisa design hai!| Mistake | Wrong ❌ | Right ✅ |
|---|---|---|
| Bina this variable set | name = name; | this.name = name; |
| this() not first line | x=5; this(10); | this(10); x=5; |
| this in static | static void m(){ this.x; } | Remove static / use object |
| Circular this | A()→B()→A() | One direction chain only |
| Both this + super | this(1); super(); | Choose one only |
ReturnThis1 hai toh file ReturnThis1.java hogi!