- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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(); } }
- Related Articles
- How does the “this” keyword work in JavaScript?
- This keyword in Java
- How to work with getDeclaringClass() in Java
- What are the 6 ways to use this keyword in Java?
- How does the reified keyword work in Kotlin?
- What are the uses of this keyword in java?
- Can we call methods using this keyword in java?
- Is it possible to use this keyword in static context in java?
- ‘this’ keyword in C#
- Can a "this" keyword be used to refer to static members in Java?
- Can we return this keyword from a method in java?
- Can we use "this" keyword in a static method in java?
- This keyword in Dart Programming
- When should I use the keyword ‘this’ in a Java class?
- How to work with border layout position options in Java?
