Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

this Keyword in Java

Last Updated on March 13, 2023 by Prepbytes

Java is considered one of the most popularly used programming languages in the world. It is widely used in the field of mobile application development and also in enterprise-level software development. Java provides a set of keywords that are predefined and have some specific meaning. this keyword in java is one of those predefined keywords. Here we will discuss about the this keyword in java in detail. Let us first learn what is a keyword in java.

Keywords in Java

As mentioned above, Java programming language contains a set of predefined keywords. These predefined keywords have some specific meaning and these cannot be used further in a Java program as an identifier (or, variable name).

Some commonly used keywords in java are:

  • abstract
  • boolean
  • break
  • byte
  • case
  • catch
  • long
  • while
  • protected
  • return
  • short
  • public
  • new
  • this
  • interface

Now let us delve deeper and learn about the this keyword in java.

this Keyword in Java

In Java, the "this" keyword refers to the current object of a class. It is used to refer to a class’s current instance variable. It may also be used to call a function constructor of a class from another constructor of the same class.

Every object in Java has a reference to itself, which may be retrieved with the "this" keyword. When you use "this" in a method, it refers to the class’s instance variable, not the method’s local variable. This makes it easy to distinguish between a class’s instance variables and local variables.

Examples Demonstrating the use of this Keyword in Java

Let’s take a look at some examples demonstrating the use of this keyword in Java.

Example 1 of use of this Keyword in Java
Using this keyword in Java to access the instance variables.

Code:

class Person {
   private String name;
   private int age;


   public Person(String name, int age) {
       this.name = name;
       this.age = age;
   }


   public void printDetails() {
       System.out.println("Name: " + this.name);
       System.out.println("Age: " + this.age);
   }
}


class Main{
  public static void main(String args[]){
     Person person = new Person("PrepBuddy", 18);
     person.printDetails();
  }
}

Output:

Name: PrepBuddy
Age: 18

Explanation:
In the above code, in printDetails() method, we use this keyword in java to access the name and age instance variables of the current Person object. This is necessary because the method has its own name and age parameters that would otherwise shadow the instance variables.

Example 2 of use of this Keyword in Java
Using this Keyword in Java to invoke another constructor in the same class.

Code:

class Rectangle {
   private int width;
   private int height;


   public Rectangle(int sideLength) {
       this(sideLength, sideLength);
   }


   public Rectangle(int width, int height) {
       this.width = width;
       this.height = height;
   }


   public int getArea() {
       return this.width * this.height;
   }
}


public class Main{
  public static void main (String args[]){
     Rectangle square = new Rectangle(45);
     System.out.println("Area of square: " + square.getArea());
     
     Rectangle rectangle = new Rectangle(4, 15);
     System.out.println("Area of rectangle: " + rectangle.getArea());
  }
}

Output:

Area of square: 2025
Area of rectangle: 60

Explanation:
The Rectangle class has two constructors, one that takes a single argument for a square and another that takes separate arguments for width and height. In the constructor that takes a single argument, we use this to call the other constructor with the same width and height. This avoids duplicating the initialization code for the width and height instance variables.

Example 3 of use of this Keyword in Java
Using this Keyword in Java to pass the current object as an argument to another method.

Code:

class BankAccount {
   private double balance;


   public BankAccount(double balance) {
       this.balance = balance;
   }


   public void deposit(double amount) {
       this.balance += amount;
       System.out.println("Deposited " + amount + ", new balance is " + this.balance);
   }


   public void transfer(BankAccount otherAccount, double amount) {
       this.balance -= amount;
       otherAccount.deposit(amount);
       System.out.println("Transferred " + amount + " from this account to other account");
   }
}


public class Main{
  public static void main(String args[]){
     BankAccount account1 = new BankAccount(5467);
     BankAccount account2 = new BankAccount(556);
     account1.transfer(account2, 444);
  }
}

Output:

Deposited 444.0, new balance is 1000.0
Transferred 444.0 from this account to other account

Explanation:
The transfer() method takes another BankAccount object and a double amount as arguments and transfers the specified amount from this account to the other account. We use this to refer to the current object instance when calling the deposit() method on the other account, passing the current account’s balance as the deposit amount. This way, the deposit amount is added to the other account’s balance and subtracted from the current account’s balance.

Example 4 of use of this Keyword in Java
Using this Keyword in Java to return the current object from a method.

Code:

class Car {
   private String make;
   private String model;


   public Car(String make, String model) {
       this.make = make;
       this.model = model;
   }


   public Car withMake(String make) {
       this.make = make;
       return this;
   }


   public Car withModel(String model) {
       this.model = model;
       return this;
   }


   public String toString() {
       return this.make + " " + this.model;
   }
}


class Main{
  public static void main(String args[]){
     Car car = new Car("Toyota", "Camry");
     car.withMake("Honda").withModel("Accord");
     System.out.println(car.toString());
  }
}

Output:

Honda Accord

Explanation:
The Car class has two methods, withMake() and withModel(), that modify the make and model instance variables respectively and return the current object instance. This allows us to chain these method calls together to set multiple properties of the object in a single statement. We use this to return the current object instance from these methods, making it easy to chain them together.

Example 5 of use of this Keyword in Java
Using this Keyword in Java to call an instance method from another instance method.

Code:

class Calculator {
   private double result;


   public Calculator() {
       this.result = 0;
   }


   public void add(double value) {
       this.result += value;
   }


   public void subtract(double value) {
       this.result -= value;
   }


   public void multiply(double value) {
       this.result *= value;
   }


   public void divide(double value) {
       if (value == 0) {
           throw new IllegalArgumentException("Division by zero");
       }
       this.result /= value;
   }


   public void clear() {
       this.result = 0;
   }


   public double getResult() {
       return this.result;
   }


   public void calculate(double value1, char operator, double value2) {
       switch (operator) {
           case '+':
               this.add(value2);
               break;
           case '-':
               this.subtract(value2);
               break;
           case '*':
               this.multiply(value2);
               break;
           case '/':
               this.divide(value2);
               break;
           default:
               throw new IllegalArgumentException("Invalid operator: " + operator);
       }
   }
}


class Main{
  public static void main(String args[]){
     Calculator calculator = new Calculator();
     
     calculator.calculate(10, '+', 5);
     System.out.println("Result: " + calculator.getResult());
     
     calculator.calculate(15, '*', 2);
     System.out.println("Result: " + calculator.getResult());
  }
}

Output:

Result: 15.0
Result: 30.0

Explanation:
The Calculator class has several methods for performing basic arithmetic operations and maintaining a current result. The calculate() method takes two operands and an operator as arguments, and performs the specified operation on the current result using one of the other instance methods. We use this to call these methods on the current object instance.

Benefits of using this Keyword in Java

Some of the benefits of this Keyword in Java are listed below.

  • Avoiding name Conflicts: Many a time, the parameter passed in the constructor have the same name as that of an instance variable already present in the class. Here, the this keyword helps the programmer in avoiding the name conflicts between the two.
  • Improving readability: The this keyword in Java helps the programmer in making the code more readable and easier to understand especially when working with complex class hierarchies.
  • Enhancing code reusability: Using "this" to call another constructor in the same class can reduce code duplication and improve code reusability.
  • Improving encapsulation: Using "this" to refer to instance variables instead of local variables can improve encapsulation and prevent accidental modifications to the wrong variable.

Conclusion
To conclude, this keyword is a powerful tool in java for referencing to the current object of a class. It is used to differentiate between a class’s instance variables and local variables, as well as to call another function constructor of the same class. So, this is an important keyword in Java programming as it helps in improving the code readability, reusability, and encapsulation.

Frequently Asked Questions (FAQs)

Here are some frequently asked questions on this keyword in Java.

Ques 1. Can we use this Keyword in Java to return a value from a constructor?
Ans. No, we cannot use the “this” keyword to return a value from a constructor as constructors do not have a return type.

Ques 2. Can “this” keyword be used to refer to a superclass?
Ans. No, we cannot use this keyword in java to refer to an object of the superclass. For performing this operation, we use the “super()” method.

Ques 3. How is the this keyword in java used to invoke another constructor in the same class?
Ans. The "this" keyword can be used to invoke another constructor in the same class by using the syntax this(argumentList).

Leave a Reply

Your email address will not be published. Required fields are marked *