Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Shane McC
3,005 PointsJava keyword "This" confused
Hi Everyone
I have a question regarding the "this" keyword in Java. When I call this.whatever in the println statement it's printing "This is from the String whatever Hi Man!!" how come it's printing "Hi Man!!" and not "Hi Dude!!"?
"Hi Dude!!" is within the scope of the method sayIt so shouldn't it print out "Hi Dude!!" instead of "Hi Dude!!"?
Thanks
public class MorePractice{
public static void main(String[] args){
Test mp = new Test ();
mp.whatever = "Hi Man!!";
mp.sayIt();
}
}
class Test{
String whatever = "Hi Dude!";
public void sayIt(){
System.out.println("This is from the String whatever " + this.whatever);
}
}
1 Answer

JT Keller
12,731 PointsDon't forget that the main method has scope as well. In addition to the scoping, the default constructor for the Test object that you've instantiated is being called, which sets your fields to (null, 0, etc... depending on the type). Think about those 2 things and retrace your steps through the code. Also adding print statements can be a good way step through your code as it is executing.