• Register

Use of java “this” keyword

At this point following is given the six use of  this keyword.

  1. it can be used to mention present class instance var.
  2. it can be used to call present present function (implicitly)
  3. it can be used to call present class constructor.
  4. it can be delivered as an argument in the function call.
  5. it can be delivered as argument in the constructor invocation.
  6. it can be used to yield the present class instance from the function.

Proposal: If you are novice to java, use only 3 usage of this keyword.

Perceiving the problem without this keyword

Let us comprehend the problem if we don't use this keyword by the sample given below:

1.	class Student1{  
2.	int rollno1;  
3.	String name1;  
4.	float fee1;  
5.	Student(int rollno1,String name1,float fee1){  
6.	rollno=rollno1;  
7.	name=name1;  
8.	fee=fee1;  
9.	}  
10.	void display(){System.out.println(rollno1+" "+name1+" "+fee1);}  
11.	}  
12.	class TestThis1{  
13.	public static void main(String args[]){  
14.	Student s11=new Student(111,"ankit",5000f);  
15.	Student s22=new Student(112,"sumit",6000f);  
16.	s11.display();  
17.	s22.display();  
18.	}}  

 

Try it Now

OutCome:

0 null 0.0

0 null 0.0

In the above sample code, parameters (proper arguments) and occurrence var are similar. Thus, we are using this keyword to differentiate local variable and instance variable.

Answer of the above Question by this keyword

1.	class Student1{  
2.	int rollno1;  
3.	String name1;  
4.	float fee1;  
5.	Student(int rollno1,String name1,float fee1){  
6.	this.rollno1=rollno1;  
7.	this.name1=name1;  
8.	this.fee1=fee1;  
9.	}  
10.	void display(){System.out.println(rollno1+" "+name1+" "+fee1);}  
11.	}  
12.	class TestThis22{  
13.	public static void main(String args[]){  
14.	Student s11=new Student(111,"ankit",5000f);  
15.	Student s22=new Student(112,"sumit",6000f);  
16.	s11.display();  
17.	s22.display();  
18.	}}  

Try it Now

OutCome:

111 ankit 5000

112 sumit 6000
2,760 points
7 4