elibraryportal Logo

this keyword in java

this keyword is used to refer to the current object inside a method or a constructor etc.

Usage of this keyword.

  • Instance variable.
  • Method
  • Constructor.
  • Passed as an argument in the method call.
  • Passed as argument in the constructor call.
  • Return the current class instance from the method.

1) this keyword used in Instance variable

this keyword can be used to refer current class instance variable.

Example 1 : by this keyword

Output

This Variable Example in java

Example 2 : problem without this keyword

Output

This Variable in java

2) this keyword used in Method

this keyword can be used to invoke the method of the current class.If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

Example :

Output

This Method in java

3) this keyword used in Constructor

→ this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

Example :

Output

This construcor Example in java

4) Pass as an argument in the method

→ this keyword can also be passed as an argument in the method. It is mainly used in the event handling.

Example :

Output

Pass as an argument in the method Example in java

5) Passed as argument in the constructor call.

We pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes.

Example :

Output

Pass as an argument in the method Example in java

6) Return the current class instance from the method..

We can return this keyword as an statement from the method.

Syntax :

Example :

Output

Return the current class instance from the method in java