Tutorials References Exercises Videos Menu
Free Website Get Certified Pro

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java Inner Classes Java Abstraction Java Interface Java Enums Java User Input Java Date Java ArrayList Java LinkedList Java HashMap Java HashSet Java Iterator Java Wrapper Classes Java Exceptions Java RegEx Java Threads Java Lambda

Java File Handling

Java Files Java Create/Write Files Java Read Files Java Delete Files

Java How To

Add Two Numbers

Java Reference

Java Keywords Java String Methods Java Math Methods

Java Examples

Java Examples Java Compiler Java Exercises Java Quiz Java Certificate


Java this Keyword

❮ Java Keywords


Example

Using this with a class attribute (x):

public class Main {
  int x;

  // Constructor with a parameter
  public Main(int x) {
    this.x = x;
  }

  // Call the constructor
  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println("Value of x = " + myObj.x);
  }
}

Try it Yourself »


Definition and Usage

The this keyword refers to the current object in a method or constructor.

The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".

this can also be used to:

  • Invoke current class constructor
  • Invoke current class method
  • Return the current class object
  • Pass an argument in the method call
  • Pass an argument in the constructor call

Related Pages

Read more about objects in our Java Classes/Objects Tutorial.

Read more about constructors in our Java Constructors Tutorial.

Read more about methods in our Java Methods Tutorial.


❮ Java Keywords