Java this Keyword

The this keyword refer to the current object inside the constructor or the method(s).

To avoid misunderstanding between class attributes and parameters with the same name in the constructor and the method, we use this keyword.

Example for this keyword

public class Main {
  String message;


  public Main(String message) {
    this.message = message;
  }

  // Call the constructor
  public static void main(String[] args) {
    Main obj = new Main("Welcome to Java");
    System.out.println("Message: "+obj.message);
  }
}

Executing the above program will generate the output,

Message: Welcome to Java

In the above example program, we have created a variable message in the Main class.

In the constructor of the Main class we have a parameter message with the same name of class variable. So we use this keyword to refer to current class object property.

Suppose in the above code if the constructor is modified like below,

  public Main(String message) {
    message = message;
  }

Now the value passed to the constructor will not be assigned to the property of the class object and the output will be empty for message variable of the class.

Message: 

Example 2 for this keyword

class Main {
   String userName;

   void setUserName(String userName) {
       this.userName = userName;
   }

   String getUserName(){
       return this.userName;
   }

   public static void main( String[] args ) {
       Main myobj = new Main();

       myobj.setUserName("Andrew");
       System.out.println("Welcome "+myobj.getUserName());
   }
}

Running this example program will print the result as,

Welcome Andrew

In the above program, we have 2 functions setUserName() and getUserName().

The setUserName() function takes a string as parameter in the userName variable, and sets the value to userName property of the class object using this keyword.

Similarly, the getUserName() function is used to return the value of the userName property of the class object.


Most Read