← Back to Chapters

Java this Keyword

? Java this Keyword

? Quick Overview

The this keyword in Java refers to the current object. It is commonly used to remove ambiguity between instance variables and parameters, call current class methods, and invoke constructors.

? Key Concepts

  • this refers to the current class object
  • Used to differentiate instance variables from parameters
  • Can call another constructor in the same class
  • Can be passed as an argument to methods

? Syntax & Theory

When local variables (method parameters) have the same name as instance variables, Java gives priority to local variables. The this keyword explicitly refers to instance variables of the current object.

? View Code Example
// Using this keyword to distinguish instance variables
class Student {
int id;
String name;

Student(int id, String name) {
this.id = id;
this.name = name;
}

void display() {
System.out.println(id + " " + name);
}
}

?️ Live Output / Explanation

Explanation

The constructor parameters id and name have the same names as instance variables. Using this.id and this.name ensures the instance variables are correctly initialized.

? Interactive Demo: The Assignment

Type in the boxes below to see how this bridges the constructor inputs to the object memory.

Constructor Parameters

this.id = id; this.name = name; ➡️

Current Object (Heap)

// Student Object
id: 0
name: "null"

✅ Tips & Best Practices

  • Always use this when parameter names match instance variables
  • Improves code readability and avoids logical errors
  • Commonly used in constructors and setter methods

? Try It Yourself

  • Create a class Employee with fields and a constructor using this
  • Modify a method to call another method using this
  • Experiment with constructor chaining using this()