Java This Keyword


In Java language, 'this' is the keyword which is a reference variable that refers to the current object. The 'this' keyword used inside any method to refer to the current object.

 

  • It is used to refer to the instance variable of the current class.
  • It is used to invoke the method of the current class.
  • It is used to invoke the constructor of the current class.

Syntax:

this 

Example:-

See the example below without using this keyword.

class Student{  
	int rollno;  
	String name; 
	Student(int rollno,String name)
    {  
        rollno=rollno;  
        name=name;  
	}  
	void showdata()
    {
    	System.out.println(rollno+" "+name); 
	} 
} 
public class Withoutthiskeyword{  
    public static void main(String args[])
    {  
        Student s1=new Student(111,"Sundarajan"); 
        Student s2=new Student(112,"Backiyalakshmi");  
        s1.showdata();  
        s2.showdata(); 
    }
}  

Example:-

See the example below using this keyword.

 class Student{  
	int rollno;  
	String name; 
	Student(int rollno,String name)
    {  
        this.rollno=rollno;  
        this.name=name;  
	}  
	void showdata()
    {
    	System.out.println(rollno+" "+name);  
	} 
} 
public class Thiskeyword{  
    public static void main(String args[])
    {  
        Student s1=new Student(111,"Sundarajan"); 
        Student s2=new Student(112,"Backiyalakshmi");  
        s1.showdata();  
        s2.showdata(); 
    }
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.