
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Work with this Keyword in Java
The this keyword in Java is mainly used to refer to the current instance variable of the class. It can also be used to implicitly invoke the method or to invoke the constructor of the current class.
A program that demonstrates the this keyword in Java is given as follows:
Example
class Student { private int rno; private String name; public Student(int rno, String name) { this.rno = rno; this.name = name; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } } public class Demo { public static void main(String[] args) { Student s = new Student(105, "Peter Bones"); s.display(); } }
Output
Roll Number: 105 Name: Peter Bones
Now let us understand the above program.
The Student class is created with data members rno, name. The constructor Student() initializes rno and name using this keyword to differentiate between local variables and instance variables as they have the same name. The member function display() displays the values of rno and name. A code snippet which demonstrates this is as follows:
class Student { private int rno; private String name; public Student(int rno, String name) { this.rno = rno; this.name = name; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } }
In the main() method, an object s of class Student is created with values 105 and "Peter Bones". Then the display() method is called. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { Student s = new Student(105, "Peter Bones"); s.display(); } }