An Overview of the Java Variable Scope

Scoping can be thought of as “the extent of information hiding.” In other words, scoping tells you where variables and methods can be seen from. Java has a neat approach to this that is both expressive and organized.

All variables are associated with a scope. Any single scope can be called a namespace. The use of namespaces allows one to associate variables with certain scopes. The benefit of using namespaces is that the programmer can use the same variable names in different scopes and ensure that variables from one section of code do not bleed into another. In other words, if multiple programmers are working on the same project more than likely they will be using the same variable names and using namespaces allows them to do so.

Scopes can do three things:

The “root” of all namespaces is the global namespace. So, all variables in the global namespace are globally scoped. Java has no global variables because it has no global namespace. Variables are scoped within a class or the method of a class. To make this even more interesting, variables that are scoped within a class are shared across all instances of that class. So, in a sense, class variables behave like global variables.

So, how does one make a namespace in Java? The use of packages accomplishes this. Java packages can be included by other packages and the variables and methods within can be accessed by the package’s prefix followed by the variable or method identifier (variable or function name).

Java uses block scoping where variables are unset at the end of a block of code. So, at the end of a class or a function the methods and variables will not live beyond that block of code. Java’s use of packages is a powerful setup and helps organize code in a very concise and expressive manner.

Published
Categorized as Java

By Joe Purcell

Joe Purcell is a technology virtuoso, cyberspace frontiersman, and connoisseur of Linux, Mac, and Windows alike.

Leave a comment