- 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
Can we return this keyword from a method in java?
The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods.
Returning “this”
Yes, you can return this in Java i.e. The following statement is valid.
return this;
When you return "this" from a method the current object will be returned.
Example
In the following Java example, the class Student has two private variables name and age. From a method setValues() we are reading values from user and assigning them to these (instance) variables and returning the current object.
public class Student { private String name; private int age; public Student SetValues(){ Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); this.name = name; this.age = age; return this; } public void display() { System.out.println("name: "+name); System.out.println("age: "+age); } public static void main(String args[]) { Student obj = new Student(); obj = obj.SettingValues(); obj.display(); } }
Output
Enter the name of the student: Krishna Kasyap Enter the age of the student: 21 name: Krishna Kasyap age: 21
- Related Articles
- Can we call a method on "this" keyword from a constructor in java?
- Can we use "this" keyword in a static method in java?
- Can we call methods using this keyword in java?
- How can we return null from a generic method in C#?
- Can we change return type of main() method in java?
- Why can't we use the "super" keyword is in a static method in java?
- This keyword in Java
- Can we call a constructor directly from a method in java?
- Can a method return multiple values in Java?
- How can we use this and super keywords in method reference in Java?
- Can we access the instance variables from a static method in Java?
- Can we call Superclass’s static method from subclass in Java?
- Can we make Array volatile using volatile keyword in Java?
- Can the main method in Java return a value?
- Can we override a protected method in Java?

Advertisements