Skip Top Navigation Bar

Scope and Access

In Java, scope and access help determine where a variable or member can be used.

Understanding scope and access helps you write code that is easier to read, safer to use, and less likely to cause errors.


Scope

A variable can only be used in the part of the program where it is defined.

Local Scope

A variable declared inside a method has local scope. It can only be used inside that method.

The variable message exists only inside printMessage().

Block Scope

A variable declared inside a block, such as an if statement or loop, has block scope. It can only be used inside that block.

The variable result exists only inside the if block.

Instance Scope

A field declared in a class, but outside any method, belongs to each object of that class. These fields can be used by all instance methods in the class.

The field name can be used by any method in Student.

Class Scope

A static field belongs to the class itself, not to any one object. A static method can access only class members directly.

The class variable studentCount is shared by all Student objects.

Access

Access controls whether a class member can be used from outside the class.

Java uses access modifiers to control access.

public

A public member can be used from anywhere the class is visible.

Any class can call displayTitle().

private

A private member can only be used inside the class where it is declared.

Other classes cannot access title directly.

Scope vs. Access

Scope and access are related, but they are not the same.

For example, a variable can have scope inside a method, but still be inaccessible outside that method because it no longer exists there.

A private field, on the other hand, exists as part of the object, but other classes are not allowed to use it directly.

Example: Scope and Access Together

In this example:

The local variable newBalance can only be used inside deposit(). The field balance can be used inside the class, but not directly from outside the class.

Why Scope and Access Matter

Scope and access help you:

When you understand scope and access, you can better decide where to declare variables and how to control the parts of your program that can use them.