java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Java this Keyword Tutorial for Beginners
Last Updated on: 25th Oct 2025 17:09:22 PM
Welcome to this complete and beginner-friendly tutorial on the this keyword in Java! The this keyword is a powerful tool in object-oriented programming that refers to the current instance of a class. It helps avoid confusion, improve code clarity, and enable advanced patterns like method chaining.
This tutorial covers all 6 major uses of this, with clear definitions, real-world analogies, and runnable examples. You can test them in any Java environment (Eclipse, IntelliJ, Repl.it, etc.).
What is the this Keyword?
this is a reference variable in Java that refers to the current object — the object on which a method or constructor is being called.
Real-World Analogy:
In a group of people named "Alex", when one says "I am Alex", they use this to refer to themselves — the current speaker.
this.name = name; // "My (this object's) name is the given name"
Why Do We Need this?
To resolve naming conflicts between:
-
Instance variables (fields of the class)
-
Local variables (parameters or variables in a method)
Without this, Java can't tell which variable you mean when names are the same.
Understanding the Problem Without this Keyword (With Example)
Let’s see what happens if we don’t use this when there’s a naming conflict.
Problem: Shadowing of Instance Variables
public class Student {
String name;
int age;
// Constructor without 'this'
public Student(String name, int age) {
name = name; // Warning! Assigns parameter to itself
age = age; // Same problem
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s = new Student("Alice", 20);
s.display();
}
}
Expected Output:
Name: Alice, Age: 20
Actual Output:
Name: null, Age: 0
Why This Happens?
-
The parameter name shadows (hides) the instance variable name.
-
name = name; assigns the parameter to itself — the instance variable is never updated!
-
The instance variables remain at their default values:
-
String → null
-
int → 0
-
Visual Explanation:
|
Variable |
Value Before |
After name = name; |
|---|---|---|
|
Parameter name |
"Alice" |
"Alice" |
|
Instance name |
null |
null (unchanged!) |
This is a common bug for beginners!
Correct Solution Using this
public Student(String name, int age) {
this.name = name; // this.name = instance variable
this.age = age; // name, age = parameters
}
Now:
-
this.name → refers to the object’s field
-
name → refers to the parameter
Output becomes correct:
Name: Alice, Age: 20
When this is NOT Required (A Program Where this is Optional)
You don’t need this when parameter names are different from instance variable names.
Example: No Naming Conflict
class Student {
int rollno;
String name;
float fee;
// Parameters have different names
Student(int r, String n, float f) {
rollno = r;
name = n;
fee = f;
}
void display() {
System.out.println(rollno + " " + name + " " + fee);
}
public static void main(String[] args) {
Student s1 = new Student(111, "Ankit", 5000f);
Student s2 = new Student(112, "Sumit", 6000f);
s1.display();
s2.display();
}
}
Output:
111 Ankit 5000.0
112 Sumit 6000.0
Explanation:
-
r, n, f are different from rollno, name, fee.
-
No shadowing → this is not needed.
-
Code works perfectly without this.
Best Practice: Use Same Names + this (Industry Standard)
In real projects, it's better to use meaningful names. So we use the same name for instance variables and parameters — and always use this keyword to avoid confusion.
Why This Approach is Preferred
|
Benefit |
Explanation |
|---|---|
|
Clarity |
this.name = name; instantly shows: “Set the object’s name to the input value” |
|
Self-Documenting |
No need for artificial names like inputName, paramAge, stdFee |
|
Consistency |
Used in major frameworks: Spring Boot, Hibernate, Android, JavaFX |
|
IDE-Friendly |
Tools like IntelliJ IDEA highlight this. fields in blue — easier to spot |
|
Less Mental Overhead |
You don’t have to remember two different names for the same concept |
Professional Example
public class User {
private String username;
private String email;
private int age;
public User(String username, String email, int age) {
this.username = username;
this.email = email;
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
// getters...
}
Clean, predictable, and widely accepted in real-world codebases.
6 Major Uses of this in Java
|
# |
Usage |
Definition |
|---|---|---|
|
1 |
this with instance variables |
Refers to the current object's fields when parameter names conflict |
|
2 |
this with methods |
Explicitly invokes another method of the current class |
|
3 |
this() |
Calls another constructor in the same class (constructor chaining) |
|
4 |
this as method argument |
Passes the current object to another method |
|
5 |
this as constructor argument |
Passes the current object to another class’s constructor |
|
6 |
return this |
Returns the current object to enable method chaining |
Let’s explore each use with definition + example.
1. this to Refer to Current Class Instance Variable
Use this to refer to the current object's field when the parameter has the same name. It removes confusion.
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name; // this.name = instance variable
this.age = age; // name, age = parameters
}
public void display() {
System.out.println("Name: " + this.name + ", Age: " + this.age);
}
public static void main(String[] args) {
Student s = new Student("Alice", 20);
s.display();
}
}
Output:
Name: Alice, Age: 20
2. this to Invoke Current Class Method
Use this.method() to call another method in the same class. It makes code easier to read.
public class Counter {
int count = 0;
public void increment() {
this.count++;
this.display(); // Calling another method
}
public void display() {
System.out.println("Count: " + count);
}
public static void main(String[] args) {
Counter c = new Counter();
c.increment();
c.increment();
}
}
Output:
Count: 1
Count: 2
3. this() to Invoke Current Class Constructor
Use this() to call another constructor in the same class. It helps reuse code.
public class Rectangle {
int length, width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
System.out.println("Two-param constructor");
}
public Rectangle(int side) {
this(side, side); // Reuse the above constructor
System.out.println("One-param constructor");
}
public void area() {
System.out.println("Area: " + (length * width));
}
public static void main(String[] args) {
Rectangle sq = new Rectangle(5);
sq.area();
}
}
Output:
Two-param constructor
One-param constructor
Area: 25
4. this as an Argument in Method Call
Passes the current object as a parameter to another method.
public class Printer {
public void print(Object obj) {
System.out.println("Printing: " + obj);
}
public void startPrinting() {
print(this); // Pass current Printer object
}
public static void main(String[] args) {
new Printer().startPrinting();
}
}
Output:
Printing: Printer@...
NOTE : Useful in callbacks, event handling, logging.
5. this as an Argument in Constructor Call
Passes the current object to another class’s constructor during object creation.
class Engine {
Engine(Car car) {
System.out.println("Engine created for: " + car);
}
}
public class Car {
Engine engine;
public Car() {
this.engine = new Engine(this); // Pass current Car object
}
public static void main(String[] args) {
new Car();
}
}
Output:
Engine created for: Car@...
NOTE : Common in dependency injection, observer pattern.
6. this to Return Current Class Instance
Returns the current object from a method to allow method chaining (fluent API).
public class Calculator {
int value = 0;
public Calculator set(int v) {
this.value = v;
return this;
}
public Calculator add(int x) {
this.value += x;
return this;
}
public void show() {
System.out.println("Result: " + value);
}
public static void main(String[] args) {
new Calculator()
.set(10)
.add(5)
.show();
}
}
Output:
Result: 15
Summary Table: All 6 Uses of this
|
# |
Usage |
Definition |
Syntax |
|---|---|---|---|
|
1 |
Instance variable |
Distinguishes field from parameter |
this.field = param; |
|
2 |
Invoke method |
Calls another method in same class |
this.method(); |
|
3 |
Invoke constructor |
Calls another constructor |
this(args); |
|
4 |
Pass to method |
Passes current object to a method |
method(this); |
|
5 |
Pass to constructor |
Passes current object to another constructor |
new Class(this); |
|
6 |
Return object |
Enables method chaining |
return this; |
When this is NOT Required
|
Case |
Example |
|---|---|
|
Different parameter names |
rollno = r; |
|
Calling methods |
display(); |
|
Accessing fields directly |
count++; |
Common Mistakes
|
Mistake |
Fix |
|---|---|
|
this() not first in constructor |
Move to line 1 |
|
Using this in static method |
Not allowed! |
|
Forgetting this in name conflict |
Always use this.field = param; |
Practice Exercise
Create a Book class with:
-
Fields: title, author, price
-
Multiple constructors
-
Method chaining: setTitle().setAuthor().setPrice().display()
Solution:
public class Book {
String title, author;
double price;
public Book() {}
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public Book setAuthor(String author) {
this.author = author;
return this;
}
public Book setPrice(double price) {
this.price = price;
return this;
}
public void display() {
System.out.println(title + " by " + author + ", $" + price);
}
public static void main(String[] args) {
new Book()
.setTitle("Java Guide")
.setAuthor("John")
.setPrice(29.99)
.display();
}
}
Final Quiz
Q: What is the output?
class Test {
int x = 5;
Test(int x) {
this.x = x;
}
void show() {
System.out.println(this.x);
}
public static void main(String[] args) {
new Test(10).show();
}
}
Answer: 10
You’ve Mastered this!
Key Takeaway:
Write clean, self-documenting code: use natural names like name, email, age for both parameters and fields — and always use this.field to assign them. It’s the modern, professional standard.
Happy Coding! ![]()
.png)