Variable Scope

Understand how variable scope defines the visibility and lifetime of variables across classes, methods, and blocks.

We'll cover the following...

As we write methods, we must understand variable scope. Variables are only available within a specific context known as their scope. Outside of a variable’s scope, the variable does not exist and cannot be accessed.

There are various scope levels:

  • Class scope: Variables declared on the class level can be accessed from any method of this class.

  • Method scope: Variables declared within a method are accessible only within this method.

  • Block scope: Like variables within a method, block-level variables are local to their scope and can’t be accessed from an outside context.