Scroll to top

this keyword in Java

What is this

this is a keyword in Java. It can be used inside the method or constructor of a class. It(this) works as a reference to the current object, whose method or constructor is being invoked. This keyword can be used to refer to any member of the current object from within an instance method or a constructor.

this keyword with a field(Instance Variable)

this keyword can be very useful in the handling of Variable Hiding. We can not create two instances/local variables with the same name. However, it is legal to create one instance variable & one local variable or Method parameter with the same name. In this scenario, the local variable will hide the instance variable this is called Variable Hiding.

Example of Variable Hiding

class JBT {

	int variable = 5;

	public static void main(String args[]) {
		JBT obj = new JBT();

		obj.method(20);
		obj.method();
	}

	void method(int variable) {
		variable = 10;
		System.out.println("Value of variable :" + variable);
	}

	void method() {
		int variable = 40;
		System.out.println("Value of variable :" + variable);
	}
}

The output of the above programme

Value of variable :10
Value of variable :40

As you can see in the example above, the instance variable is hiding, and the value of the local variable (or Method Parameter) is displayed not instance variable. To solve this problem use this keyword with a field to point to the instance variable instead of the local variable.

Example of this keyword in Java for Variable Hiding

class JBT {

	int variable = 5;

	public static void main(String args[]) {
		JBT obj = new JBT();

		obj.method(20);
		obj.method();
	}

	void method(int variable) {
		variable = 10;
		System.out.println("Value of Instance variable :" + this.variable);
		System.out.println("Value of Local variable :" + variable);
	}

	void method() {
		int variable = 40;
		System.out.println("Value of Instance variable :" + this.variable);
		System.out.println("Value of Local variable :" + variable);
	}
}

The output of the above program

Value of Instance variable :5
Value of Local variable :10
Value of Instance variable :5
Value of Local variable :40

this Keyword with Constructor

“this” keyword can be used inside the constructor to call another overloaded constructor in the same Class. It is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded constructors, one without argument and another with the argument. Then this” keyword can be used to call the constructor with an argument from the constructor without argument. This is required as the constructor cannot be called explicitly.

Example of this with Constructor

class JBT {

	JBT() {
		this("JBT");
		System.out.println("Inside Constructor without parameter");
	}

	JBT(String str) {
		System.out
				.println("Inside Constructor with String parameter as " + str);
	}

	public static void main(String[] args) {
		JBT obj = new JBT();
	}
}

The output of the above program

Inside Constructor with String parameter as JBT
Inside Constructor without parameter

As you can see “this” can be used to invoke an overloaded constructor in the same Class.

Note*:

  • this keyword can only be the first statement in Constructor.
  • A constructor can have either this or super keyword but not both.

this Keyword with Method

this keyword can also be used inside Methods to call another Method from same Class.

Example of this keyword with Method

class JBT {

	public static void main(String[] args) {
		JBT obj = new JBT();
		obj.methodTwo();
	}
	void methodOne(){
		System.out.println("Inside Method ONE");
		}

	void methodTwo(){
		System.out.println("Inside Method TWO");
		this.methodOne();// same as calling methodOne()
	}
}

The output of above program

Inside Method TWO
Inside Method ONE

Example of this keyword as a Method parameter

public class JBTThisAsParameter {

	public static void main(String[] args) {
		JBT1 obj = new JBT1();
		obj.i = 10;
		obj.method();
	}

}

class JBT1 extends JBTThisAsParameter {
	int i;

	void method() {
		method1(this);
	}

	void method1(JBT1 t) {
		System.out.println(t.i);
	}
}

If you understood this keyword correctly, next step should be to understand Static Keyword in Java from Java Tutorial.

References
1- Official Document

Author avatar
JBT
https://javabeginnerstutorial.com/

69 comments

  1. Janith

    Example of this with Constructor has mistake.Can you please make it correct.

  2. arun

    this was very helpful..thanks

  3. mukesh

    very nice tutorial .

  4. krishna

    Very nice explanations…

    Thanks alot …

  5. root

    Thank you… it helped a lot ..!

  6. DannyS

    Scoured the internet to get clarification on this (pun intended). The light bulb finally went on. Thanks.

  7. Abhishek

    the given example this keyword is not best use in method level because without this you can call method…………………………………………………. so please give me best example of this keyword in method level………

    • Vivekanand Gautam

      Hi Abhishek,

      I am agree with you given example is not best example for this @Method level. But i couldn’t think of any other example for the same. Meanwhile i have added an example for Method parameter. WHich might be helpful to you. Would update the article in future in case i get any example.

      Thanks

  8. Salil Chawla

    Very helpful tutorial

  9. Mubeen ali

    First of all i thank you
    this tutorial was very useful for me.

  10. Nishant

    really a very cool website.liked your tutorials,very simple and easy

  11. ram

    i need a answer for following program
    write a java program to implement the usage of “this” keyword for the following cases
    1. to refer the current class instance variable.
    2. to invoke the current class constructor
    3. to invoke the current class method
    4. to return current class instance
    i need all in one programs with simple codeing…….
    i am waiting …!

    • Prabhakar

      import java.util.Scanner;

      class Bank
      {
      int accno;
      String name;
      int bal;

      Bank(int accno,String name)
      {
      this.accno=accno;
      this.name=name;

      }
      Bank(int accno,String name,int bal)
      {
      this(accno,name);
      this.bal=bal;
      }

      public void show_details()
      {
      System.out.println(“Accno=”+accno);
      System.out.println(“Name=”+name);
      System.out.println(“Balance=”+bal);
      }
      public void deposit()
      {
      System.out.println(“Enter Amount to be deposit”);
      Scanner sc=new Scanner(System.in);
      int amount=sc.nextInt();
      bal=bal+amount;
      show_details();
      }
      }
      public class Ex_this
      {

      public static void main(String[] args) {
      Bank b1=new Bank(1001,”Hari”,1000);
      b1.show_details();
      b1.deposit();

      }

      }

  12. yogaraj

    Very nice.am easily understand

  13. Sandu

    Nice explanation. Thank you so much.

  14. mukta

    I is not declared in the example of method to parameter, not necessary??

  15. mukta

    I mean method parameter.. Isn’t generate any error??

  16. dinesh sharma

    very nice explanation,thanx!

  17. nura

    it helped me a lot

  18. pooja

    Thank u soo much for helped me.. a good example

  19. Hash

    Thank you so much

  20. Hash

    Can you please give the output for the last Example of this keyword as Method parameter. I need only this output for understanding

  21. Srinivas

    this one easy understanding program thanks…

  22. Hena Girl

    If some one needs to be updated with most recent technologies afterward he must be visit this website and be up to date daily.

  23. anon

    where is the output of the last program?

  24. Swad

    got a clean idea.. Thanks.

  25. Anil

    Nice…very helpful

  26. Bobby Smither

    “This” helped a lot

  27. arvind yadav

    very nice explanation,thnks alot——

  28. Rj Awais

    wow
    nice sharing sir love this site……..

  29. uma

    Write a program in Java to implement Method Overloading in java by using “this” keyword ?

  30. Manjot

    in which class this() method has been defined

  31. Goran

    Great and complete explanation of the word “this”. Something basic that many faculty professors wont tell their students…

  32. Priya

    It is very important concept in java .This keyword is a reference variable that refer the current object in java. This keyword can be used for call current class constructor.

  33. Pranav

    Thnx a lot sir….

  34. Vijay

    I want to know following statement explanation
    int method()
    {
    return this.variable;
    }
    here return statement done what task.
    Why this place we use.

  35. Akbar

    nice
    easy to understand

  36. Hari

    Elegant content helps me a lot. Thanks

  37. Shashira

    Interesting. This is very helpful. Thank you !

  38. Ahshan Alam

    This one is very helpful to understand “this “

  39. Javaaspirant

    class JBT {
    public static void main(String[] args) {
    JBT obj = new JBT();
    obj.methodTwo();
    }
    void methodOne(){
    System.out.println(“Inside Method ONE”);
    }
    void methodTwo(){
    System.out.println(“Inside Method TWO”);
    this.methodOne();// same as calling methodOne()
    }
    }

    when I removed ‘this’ from the line this.methodOne();// same as calling methodOne() I get the same output. Is this the standard behaviour ?

    • JBT

      Yes, that is standard behavior. this is just used to point to the current object and in this case, it is the current object’s method. So it will get called.

  40. Uttam Sawad

    class car
    {
    int speed;
    car()
    {
    speed=70;
    }
    protected void finalize()
    {
    System .out.println(“destroy object of car”);
    }
    }
    class bike
    {
    int speed;
    bike()
    {
    speed=70;
    }
    protected void finalize()
    {
    System.out.println(“destroy object of bike”)
    }
    }
    class Garbage_Collection
    {
    public static void main(String []args)
    {
    car c=new car();
    bike b=new bike();
    b=null;
    System.gc();
    System.out.println(“speed of car: “+c.speed);
    }
    }

Post a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.