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! While you're at it, check out some resources Treehouse students have shared here.
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
Matthew Francis
6,967 PointsNewbie Question - Declaration order
I'm wondering why in this code:
class Bob{
void method1(){
System.out.println("method2");
method1(); //Edited to method1(), instead of method2()
}
void method1(){
System.out.println("method2");
}
}
method2() will get invoked, even after it is created after the declaration, what is the compiler acutally doing?
While in this code:
class Bob{
System.out.println(red);
String red = "red";
}
System.out.println(red) is unable to find what "red" means, if you can reference it before creating it (like in the first example), why won't this work?
1 Answer
Jennifer Nordell
Treehouse TeacherI'll give it a shot! Ok I'm assuming that in your first example the second method is supposed to be method2 although you actually have two separate method1 listed. When you declare the method and define it, you create the method. But that doesn't mean you're actually executing it right now. So when you finally get around to executing method1, it in turn, executes method2. But method 2 has already been declared and built and is ready to go.
In your "red" example, you're trying to print the value of a variable you haven't yet declared. And Java doesn't allow that.
Hope this helps and makes sense!
Matthew Francis
6,967 PointsMatthew Francis
6,967 PointsThanks again!