Scope


Premium Content - Free Preview

As mentioned in Accessors and Modifiers, some variables are only available within a certain method, while other variables are available to all of the code in the Class.

The area of code that a variable is available to, is known as the scope. A scope (or "block") is normally specified by curly-braces in Java. BlueJ marks the different scopes with different colors, so you can see them more clearly:

BlueJ Scope Example

You can view the different levels of scope as different colors, from the Class to the Methods to the Loops within methods. (The code editor on this site does not mark scopes with colors, but it does put little arrows on the side for collapsing and expanding them.)

Any variable declared in a specific scope is available only to that scope (except for non-private instance variables). Code outside of that scope cannot access that variable. In fact, the variable gets deleted once its scope of code finishes running.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

  • I have the correct answer now, but first of all I thought it would be 16. I didn't think the call to the doubleTotal method would actually change the value of the total variable, because the method is void and the new total doesn't get returned as an integer.

  • How it works then with void? It only do something there, change the value, but type for total is taken from the beginning of the class, when int total; is defined <

  • total is available to the whole instance, so doubleTotal will double it for all the code that uses it. In general, variables are available to the entire scope (marked with {}) that they are declared in.

    cont...
  • Thanks a lot as always

  • Can't do the last challenge because the picture isn't loading

    Image placeholder with title "colored-code"

  • Sorry about that, it's been fixed.

Contact Us
Sign in or email us at [email protected]