Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

November 22, 2014 Categories: Core Java Basics. No Comments on this Keyword

In this article, we will look at the uses of this keyword in Java programs along with example Java code.


Introduction to this Keyword


this keyword in Java is used to refer current object on which a method is invoked. Using such property, we can refer the fields and other methods inside the class of that object. The this keyword has two main uses which are listed below:

  1. It is used to eliminate ambiguity between fields and method parameters having the same name.
  2. It is used for chaining constructors.


To explain the first use, let’s consider the following program, which creates a square and displays it:



In the above code segment, there are no errors as the field name side and parameter name s are different. Now, let’s modify our Square class as shown below:



In the above code segment, observe line no: 6. At this line, JVM will be in a ambiguous situation to decide whether to initialize the field side or the parameter side. To eliminate such ambiguity, the left side variables can be preceded with this keyword as shown below:



Now, JVM will be able to decide that the left hand side variable is the field side, and the right hand side variable is the parameter side.


Some programmers prefer to declare fields and parameters with different names and other programmers prefer the same names for both fields and parameters. Which one to practice, is left to you.


The second use of this keyword is constructor chaining, which refers to the invocation of one constructor from another constructor. We can call a constructor from another constructor using this keyword as shown below:


this(param1, param2, …, paramn);


While using the above syntax, the constructor whose signature (number of and type of parameters) matches, will be invoked.


Note: While invoking another constructor using the this keyword, it should be the first line inside the constructor’s definition. For clarity regarding this, look at the example given below:


Example on constructor chaining:



In the above program, at line number 6, the second constructor is invoked as it is having a single integer parameter and 4 is passed to the parameter s which will be assigned to the field, side.

Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up