How to Use the Java Keyword this - dummies

How to Use the Java Keyword this

By Doug Lowe

The keyword this in Java refers to the current class instance. For example, if a class defines a method named Calculate, you can call that method from another method within the same class like this:


Of course, you can also call the Calculate method without the this keyword:


Thus, in most cases, the keyword this is not necessary.

However, sometimes the this keyword can come in handy. For example:

public class Actor
    string lastName;
    string firstName;
    public Actor(String lastName, String firstName)
        this.lastName = lastName;
        this.firstName = firstName;

The this keywords are required to distinguish among the parameters named lastName and firstName and the instance.

Sometimes, you use the this keyword by itself to pass a reference to the current object as a method parameter. You can print the current object to the console by using the following statement:


The println method calls the object’s toString method to get a string representation of the object and then prints it to the console. By default, toString prints the name of the class that the object was created from and the object’s hash code. If you want the println method to print something more meaningful, provide a toString method of your own for the class.