Scope

The scope of a variable refers to the parts of a class within which the variable exists and can be used. The basic rule is that a variable exists only within the block in which it is declared. (In Java, a block is defined by a matching set of braces.)

That is why class and instance variables, which are declared in the class body, can be accessed by any methods defined by the class. Comparatively, local variables defined within a method can be accessed only by the method in which they are defined.

TechnicalStuff.eps Strictly speaking, the scope of a local variable begins when the variable is initialized and ends when the block that contains the variable’s declaration ends. By contrast, the scope for a class or instance variable is the entire class in which the variable is declared. That means that you can use a class or instance variable in a method that physically appears before the variable is declared, but you can’t use a local variable before it’s declared.

CrossRef.eps For information about creating class, instance, and local variables, see Class Variables, Instance Variables, and Local Variables. For information about using variables whose scopes overlap, see Shadowing.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.