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 trialRobert Kwiat
5,349 PointsScoping
Can somebody please define scoping in their own words? Thanks!
1 Answer
Aaron Arkie
5,345 PointsSure, i'll give it a go!
so if we create a method called code() and after the curly braces where there is space where all the code goes you are creating whats called a block. A block defines a scope.
code() { // <---Scope
BLOCK
} //end Scope
Every time you create a new method, class, or statement a block of code is created a scope concurrently will also be created! But beware, variables or objects defined in a block of code or scope that's not in the main scope will not exist outside of its scope.
so let me give you a better example.
class example{ //start of class scope
public static void main(String[] args) { // main scope
int A = 7; // this is known to your entire program since its in the main Scope.
if(A==7) { // a new set of curly braces = a new Scope
int B = 2; // this variable is only known to this scope
//A is known here since it was defined in the main scope.
Sytem.out.println("A and B are: " + A + " and " + B)
} //end of IF scope.
//we are now in the main Scope again
B = 5; // B is not known here because it is out of its scope
// A is still valid because we are now in the main scope.
Sytem.out.println("A holds the value of: " + A)
}//end of main scope
} //end of class scope
the output will be:
- A and B are: 7 and 2; // the if scope
- A holds the value of 7;
If we were to have included B inside this print statement:
Sytem.out.println("A holds the value of: " + A + " and" + B)
We would have reached an error because B does not exist outside its scope.
So just remember this:
Variables are declared once a scope has been created and are only "alive" inside there own scope. If a variable leaves it's scope it is destroyed!
I hope this helps! Goodluck!