This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Keyword this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Keyword this" Watch "Keyword this" New topic
Author

Keyword this

J Brewer
Ranch Hand

Joined: Jul 10, 2006
Posts: 46
Given:

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
this.i refers to the class variable i in this case since this is a reference to an object of type Test.

The i declared inside the method is a local variable.
Maureen Augustus
Ranch Hand

Joined: Aug 18, 2006
Posts: 72
Hi J,

Because "int i = 20" is defined within a method, it is a local variable, not an instance variable.

The this keyword references instance variables, like the one you defined with the code "public static int i =99" and then assigned the value 10 within the method.

If you want to display the value "20", your output line would read "System.out.println(i);" to access the local variable instead of the instance variable.


"Sex and drugs and women being set on fire! I've never heard of such a Christmas!" - Christine Baranski in "The Ref"
J Brewer
Ranch Hand

Joined: Jul 10, 2006
Posts: 46
Ah, so the 'this' keyword refers to the instance or class variable, but not to a local variable. Gotcha.

Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Keyword this
 
Similar Threads
Qn on Overriding concept.
init blocks and constructor chain
static variable confusion
Finalize() method question
static keyword over a block