The "this" keyword in JAVA

When you program in JAVA, you are most likely to do something with functions. There, the "this" keyword can be a useful companion.

Lets say you have a function where you take some inputs and do something with it.

String name = "Jessica";
public void MyFunction(String inputName){
      System.out.println("the old name is: " + name);
      name = inputName;
      System.out.println("the new name is: " + name);
}

This function asks for your input to change the name "Jessica" with something new. But there is a better solution including the "this" keyword, which avoids choosing a new title for the input variable.

String name = "Jessica";
public void MyFunction(String name){
      System.out.println("the old name is: " + name);
      this.name = name;
      System.out.println("the new name is: " + name);
}

As you can see, with the help of the "this" keyword, you can skip the whole naming thing of a new variable and get the same output.

The "this" keyword refers to the object currently being executed and makes your code look much more clean with shorter variable-names and gives it even a professional impression. I would recommend to use "this" always in these situations.

This article was updated on October 7, 2024

Hey, I am David, the owner of this blog.
Feel free to have look around and read the articels I write.