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

 Live Demo

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();
   }
}

Updated on: 30-Jul-2019

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements