Can you explain me clearly why we use this keyword in java | Core Java Forum
H
Harika Posted on 07/07/2023

what is the use of this keyword in java with example.


Y
Yogesh Chawla Replied on 07/07/2023

this refers to the current class object.
this keyword basically resolves the ambiguity between instance variable, local variable and method parameter.

See this example how this is maintaining the instance variable value intact whereas local variable value is different

 

class Student {

	int id = 5;

	Student() {
		int id = 10;
		System.out.println("Value of name variable :" + id);
		System.out.println("Value of name variable :" + this.id);
	}

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

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

	void method2() {
		id = 25;
		System.out.println("Value of Instance variable :" + this.id);
		System.out.println("Value of Local variable :" + id);
	}

	public static void main(String args[]) {
		Student obj = new Student();
		obj.method();
		obj.method(20);
		obj.method2();
	}
}