File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes this-operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this-operator" Watch "this-operator" New topic


nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
What is best-practice:

Should I write the "this"-Operator explicitly or can I delete it?

What is better?


I know, it makes no difference but I have a lot of this.-in my java-files and want to delete the "this".

Should I do that?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

It's up to you, it depends on what style you personally prefer. If you add the "this", it makes it explicitly clear that you're calling a method on the current object. Personally, I prefer to not use the "this" too much in Java.

Note: "this" is not an operator, it's simply a reference to the current object.
[ October 24, 2008: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457

I was redirected here from

a topic moved from Advanced to Beginner (but linking to the wrong one)

Bill Shirley - bshirley -
if (Posts < 30) JavaRanchFAQ);
Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105
Consider an example

if you don't use this.i here with instance variable then constructor will explicitly assign the value of local variable i to itself.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46334
Agree; that is a situation where the this keyword is necessary. [pedantic mode]But it's not a local variable you are reasigning; it's the parameter being reassigned to itself.[/pedantic mode]
I agree. Here's the link:
subject: this-operator
jQuery in Action, 3rd edition