this keyword

In Java, this is a keyword that refers to the current object — the object on which the method or constructor is being called.

In simple words: this means "myself" (the current object).


Why do we need this?

Let’s say you have a variable called name, and you also pass a parameter named name to a constructor. How will Java know which one you're talking about?

That’s where this comes in.


Example 1: When variable names are the same

public class Student {
    String name;
    Student(String name) {
        this.name = name; // 'this.name' refers to instance variable
      // whereas name refers to parameter
    }
    void display() {
        System.out.println("Name: " + this.name);
    }
}

Output:

Name: Rahul

In the constructor, this.name refers to the variable inside the class, and name is the parameter passed to the constructor.


Example 2: Calling another constructor using this()

You can use this() to call another constructor from the same class.

public class Student {
    String name;
    int age;
    Student() {
        this("Default", 18); // calling the other constructor
    }
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    void display() {
        System.out.println(name + ", " + age);
    }
}

Example 3: Passing current object using this

Sometimes you might want to pass the current object to another method.

public class Student {
    String name;
    Student(String name) {
        this.name = name;
    }
    void print(Student s) {
        System.out.println("Student name is: " + s.name);
    }
    void show() {
        print(this); // passing current object
    }
}

Summary

Use Case How this helps
Variable name conflict Distinguishes between instance and local variables
Calling another constructor this() calls another constructor in the same class
Passing current object this can be passed to methods or constructors