The Wayback Machine - https://web.archive.org/web/20240909214717/https://www.geeksforgeeks.org/this-reference-in-java/
Open In App

‘this’ reference in Java

Last Updated : 08 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a keyword that refers to the current object instance. It can be used to call current class methods and fields, to pass an instance of the current class as a parameter, and to differentiate between the local and instance variables. Using “this” reference can improve code readability and reduce naming conflicts.

Java this reference Example 

In Java, this is a reference variable that refers to the current object on which the method or constructor is being invoked. It can be used to access instance variables and methods of the current object.

Below is the implementation of this reference:

Java




// Java Program to implement
// Java this reference
 
// Driver Class
public class Person {
 
    // Fields Declared
    String name;
    int age;
 
    // Constructor
    Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
 
    // Getter for name
    public String get_name() { return name; }
 
    // Setter for name
    public void change_name(String name)
    {
        this.name = name;
    }
 
    // Method to Print the Details of
    // the person
    public void printDetails()
    {
        System.out.println("Name: " + this.name);
        System.out.println("Age: " + this.age);
        System.out.println();
    }
 
    // main function
    public static void main(String[] args)
    {
        // Objects Declared
        Person first = new Person("ABC", 18);
        Person second = new Person("XYZ", 22);
 
        first.printDetails();
        second.printDetails();
 
        first.change_name("PQR");
        System.out.println("Name has been changed to: "
                           + first.get_name());
    }
}


Output

Name: ABC
Age: 18

Name: XYZ
Age: 22

Name has been changed to: PQR

Explanation

In the above code, we have defined a Person class with two private fields name and age. We have defined the Person class constructor to initialize these fields using this keyword. We have also defined getter and setter methods for these fields which use this keyword to refer to the current object instance.

In the printDetails() method, we have used this keyword to refer to the current object instance and print its name, age, and object reference.

In the Main class, we have created two Person objects and called the printDetails() method on each object. The output shows the name, age, and object reference of each object instance.

Methods to use ‘this’ in Java

Following are the ways to use the ‘this’ keyword in Java mentioned below:

  • Using the ‘this’ keyword to refer to current class instance variables.
  • Using this() to invoke the current class constructor
  • Using ‘this’ keyword to return the current class instance 
  • Using ‘this’ keyword as the method parameter
  • Using ‘this’ keyword to invoke the current class method 
  • Using ‘this’ keyword as an argument in the constructor call

1. Using ‘this’ keyword to refer to current class instance variables

Java




// Java code for using 'this' keyword to
// refer current class instance variables
class Test {
    int a;
    int b;
 
    // Parameterized constructor
    Test(int a, int b)
    {
        this.a = a;
        this.b = b;
    }
 
    void display()
    {
        // Displaying value of variables a and b
        System.out.println("a = " + a + "  b = " + b);
    }
 
    public static void main(String[] args)
    {
        Test object = new Test(10, 20);
        object.display();
    }
}


Output

a = 10  b = 20

2. Using this() to invoke current class constructor

Java




// Java code for using this() to
// invoke current class constructor
class Test {
    int a;
    int b;
 
    // Default constructor
    Test()
    {
        this(10, 20);
        System.out.println(
            "Inside  default constructor \n");
    }
 
    // Parameterized constructor
    Test(int a, int b)
    {
        this.a = a;
        this.b = b;
        System.out.println(
            "Inside parameterized constructor");
    }
 
    public static void main(String[] args)
    {
        Test object = new Test();
    }
}


Output

Inside parameterized constructor
Inside  default constructor 


3. Using ‘this’ keyword to return the current class instance 

Java




// Java code for using 'this' keyword
// to return the current class instance
class Test {
    int a;
    int b;
 
    // Default constructor
    Test()
    {
        a = 10;
        b = 20;
    }
 
    // Method that returns current class instance
    Test get() { return this; }
 
    // Displaying value of variables a and b
    void display()
    {
        System.out.println("a = " + a + "  b = " + b);
    }
 
    public static void main(String[] args)
    {
        Test object = new Test();
        object.get().display();
    }
}


Output

a = 10  b = 20

4. Using ‘this’ keyword as a method parameter

Java




// Java code for using 'this'
// keyword as method parameter
class Test {
    int a;
    int b;
 
    // Default constructor
    Test()
    {
        a = 10;
        b = 20;
    }
 
    // Method that receives 'this' keyword as parameter
    void display(Test obj)
    {
        System.out.println("a = " + obj.a
                           + "  b = " + obj.b);
    }
 
    // Method that returns current class instance
    void get() { display(this); }
 
    // main function
    public static void main(String[] args)
    {
        Test object = new Test();
        object.get();
    }
}


Output

a = 10  b = 20

5. Using ‘this’ keyword to invoke the current class method 

Java




// Java code for using this to invoke current
// class method
class Test {
 
    void display()
    {
        // calling function show()
        this.show();
 
        System.out.println("Inside display function");
    }
 
    void show()
    {
        System.out.println("Inside show function");
    }
 
    public static void main(String args[])
    {
        Test t1 = new Test();
        t1.display();
    }
}


Output

Inside show function
Inside display function

6. Using ‘this’ keyword as an argument in the constructor call

Java




// Java code for using this as an argument in constructor
// call
// Class with object of Class B as its data member
class A {
    B obj;
 
    // Parameterized constructor with object of B
    // as a parameter
    A(B obj)
    {
        this.obj = obj;
 
        // calling display method of class B
        obj.display();
    }
}
 
class B {
    int x = 5;
 
    // Default Constructor that create an object of A
    // with passing this as an argument in the
    // constructor
    B() { A obj = new A(this); }
 
    // method to show value of x
    void display()
    {
        System.out.println("Value of x in Class B : " + x);
    }
 
    public static void main(String[] args)
    {
        B obj = new B();
    }
}


Output

Value of x in Class B : 5

Advantages of using ‘this’ reference

There are certain advantages of using ‘this’ reference in Java as mentioned below:

  1. It helps to distinguish between instance variables and local variables with the same name.
  2. It can be used to pass the current object as an argument to another method.
  3. It can be used to return the current object from a method.
  4. It can be used to invoke a constructor from another overloaded constructor in the same class.

Disadvantages of using ‘this’ reference

Although ‘this’ reference comes with many advantages there are certain disadvantages of also:

  1. Overuse of this can make the code harder to read and understand.
  2. Using this unnecessarily can add unnecessary overhead to the program.
  3. Using this in a static context results in a compile-time error.
  4. Overall, this keyword is a useful tool for working with objects in Java, but it should be used judiciously and only when necessary.

This article is contributed by Mehak Narang and Amit Kumar



Previous Article
Next Article

Similar Reads

java.lang.ref.Reference Class in Java
java.lang.ref.Reference Class is an abstract base class for reference object. This class contains methods used to get information about the reference objects. This class is not a direct subclass because the operations on the reference objects are in close co-operation with the garbage collector. Class declaration: prevent public abstract class Refe
3 min read
How to pass integer by reference in Java
Java is pass by value and it is not possible to pass integer by reference in Java directly. Objects created in Java are references which are passed by value. Thus it can be achieved by some methods which are as follows: By creating Wrapper Class: As we know that Integer is an immutable class, so we wrap an integer value in a mutable object through
4 min read
Different Ways to Achieve Pass By Reference in Java
There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and actual parameters through code: Java Code // Java pr
5 min read
Backwards Compatibility in a Software System with Systematic Reference to Java
Here we will be discussing a way to achieve “Backwards Compatibility” while developing new features in any software system. So let us do a brief about backward compatibility in brief. Backward compatibility is a property of a system, product, or technology that allows for integration with an older legacy system or with an input designed for such a
5 min read
Passing Strings By Reference in Java
In Java, variables of primitive data types, such as int, char, float, etc., are passed by value, meaning that a copy of the variable's value is passed to a method or function. However, when it comes to passing objects, including Strings, the concept of passing by reference versus passing by value can be confusing. In this blog post, we will explore
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Referencing Subclass objects with Subclass vs Superclass reference
Prerequisite : Inheritance In Java, all non-static methods are based on the runtime type of the underlying object rather than the type of the reference that points to that object. Therefore, it doesn't matter which type you use in the declaration of the object, the behavior will be the same. How to Refer a subclass object There are two approaches t
6 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m <= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read
Java.math.BigInteger.probablePrime() method in Java
Prerequisite : BigInteger Basics The probablePrime() method will return a Biginteger of bitLength bits which is prime. bitLength is provided as parameter to method probablePrime() and method will return a prime BigInteger of bitLength bits. The probability that a BigInteger returned by this method is composite and does not exceed 2^-100. Syntax: pu
2 min read
Java | How to start learning Java
Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in
5 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supp
2 min read
Practice Tags :