Menu
×
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

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 this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Enums Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator

Java File Handling

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

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting

Java How To's

Add Two Numbers Count Words Reverse a String Sum of Array Elements Convert String to Array Sort an Array Find Array Average Find Smallest Element ArrayList Loop HashMap Loop Loop Through an Enum Area of Rectangle Even or Odd Number Positive or Negative Square Root Random Number

Java Reference

Java Reference Java Keywords Java String Methods Java Math Methods Java Output Methods Java Arrays Methods Java ArrayList Methods Java LinkedList Methods Java HashMap Methods Java Scanner Methods Java Iterator Methods Java Errors & Exceptions

Java Examples

Java Examples Java Compiler Java Exercises Java Quiz Java Server Java Syllabus Java Study Plan Java Certificate


Java this


Java this Keyword

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

The this keyword is often used to avoid confusion when class attributes have the same name as method or constructor parameters.


Accessing Class Attributes

Sometimes a constructor or method has a parameter with the same name as a class variable. When this happens, the parameter temporarily hides the class variable inside that method or constructor.

To refer to the class variable and not the parameter, you can use the this keyword:

ExampleGet your own Java Server

public class Main {
  int x;  // Class variable x

  // Constructor with one parameter x
  public Main(int x) {
    this.x = x; // refers to the class variable x
  }

  public static void main(String[] args) {
    // Create an object of Main and pass the value 5 to the constructor
    Main myObj = new Main(5);
    System.out.println("Value of x = " + myObj.x);
  }
}

Output:

Value of x = 5

Try it Yourself »

Tip: Think of this.x = x; as: "this.x (the class variable) gets the value of x (the parameter)."

Without this, the code above x = x; would set the parameter x equal to itself, and the class variable would stay uninitialized (0).


Calling a Constructor from Another Constructor

You can also use this() to call another constructor in the same class.

This is useful when you want to provide default values or reuse initialization code instead of repeating it.

Example

public class Main {
  int modelYear;
  String modelName;

  // Constructor with one parameter
  public Main(String modelName) {
    // Call the two-parameter constructor to reuse code and set a default year    
    this(2020, modelName);
  }

  // Constructor with two parameters
  public Main(int modelYear, String modelName) {
    // Use 'this' to assign values to the class variables
    this.modelYear = modelYear;
    this.modelName = modelName;
  }

  // Method to print car information
  public void printInfo() {
    System.out.println(modelYear + " " + modelName);
  }

  public static void main(String[] args) {
    // Create a car with only model name (uses default year)
    Main car1 = new Main("Corvette");

    // Create a car with both model year and name
    Main car2 = new Main(1969, "Mustang");

    car1.printInfo();
    car2.printInfo();
  }
}

Output:

2020 Corvette
1969 Mustang

Try it Yourself »

Note: The call to this() must be the first statement inside the constructor.


When to use this?

  • When a constructor or method has a parameter with the same name as a class variable, use this to update the class variable correctly.
  • To call another constructor in the same class and reuse code.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.