What is ‘this’ keyword in java? Explained with example.

 The “this” keyword in Java is used to refer to the current object of a class. It is used to access the current object’s properties and methods, and it can also be used to invoke constructors of the same class.

For example, consider the following class:


class MyClass {
    int x;
    MyClass(int x) {
        this.x = x;
    }
    void display() {
        System.out.println("Value of x: " + this.x);
    }
}

In this example, the class “MyClass” has a constructor that takes an integer as a parameter and assigns it to the variable “x” of the class. The “this” keyword is used to refer to the current object’s variable “x”.

The “this” keyword can also be used to invoke constructors of the same class, like this:


class MyClass {
    int x;
    MyClass() {
        this(5);
    }
    MyClass(int x) {
        this.x = x;
    }
    void display() {
        System.out.println("Value of x: " + this.x);
    }
}

In this example, the MyClass class has two constructors. One is the default constructor and the other one takes an integer as a parameter. The default constructor uses the “this” keyword to invoke the other constructor and passing the value of 5 as a parameter. So, if the object is created using the default constructor, it will set the value of x as 5.

The “this” keyword can also be used to pass the current object as an argument to a method or a constructor. Like this:


class MyClass {
    int x;
    MyClass(int x) {
        this.x = x;
    }
    void display(MyClass obj) {
        System.out.println("Value of x: " + obj.x);
    }
}

In this example, the display method takes an object of the MyClass class as a parameter. If you want to pass the current object as an argument to this method, you can use “this” keyword like this:


MyClass obj1 = new MyClass(10);
obj1.display(this);
The output of this code would be "Value of x: 10"

In conclusion, the “this” keyword in Java is used to refer to the current object of a class. It is used to access the current object’s properties and methods, and it can also be used to invoke constructors of the same class. It can also be used to pass the current object as an argument to a method or a constructor. The “this” keyword is a powerful tool that allows developers to access the functionality of the current object within the same class.