What is the this Keyword in Java?
The this keyword refers to the current object instance. It is used to access instance variables, call other constructors, and pass the current object as a parameter.
1. Refer to Instance Variables
class Student {
int rollNo;
String name;
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
}
2. Call Another Constructor
class Employee {
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
Employee() {
this(0, "Default");
}
}
3. Return Current Object
class Calculator {
int value;
Calculator add(int num) {
this.value += num;
return this;
}
Calculator multiply(int num) {
this.value *= num;
return this;
}
void print() {
System.out.println("Value: " + value);
}
}
// Usage
new Calculator().add(5).multiply(2).print();
Master Java programming with Online Learner!
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
