Scope of Variables In Java

In programming, scope of variable defines how a specific variable is accessible within the program or across classes. In this section, we will discuss the scope of variables in Java.

In Java, there are two types of variables based on their scope:

  1. Member Variables (Class Level Scope)
  2. Local Variables (Method Level Scope)

Member Variables (Class Level Scope)

These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class. Let’s take a look at an example: 

public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}
  • We can declare class variables anywhere in class, but outside methods.
  • Access specified of member variables doesn’t affect scope of them within a class.
  • Member variables can be accessed outside a class with following rules
Access Modifier
Package
Subclass
Word
public
Yes
Yes
Yes
protected
Yes
Yes
No
private
No
No
No
default
Yes
No
No

Local Variables (Method Level Scope)

Variables declared inside a method have method level scope and can’t be accessed outside the method. 

public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}

Note : Local variables don’t exist after method’s execution is over. 

Here’s another example of method scope, except this time the variable got passed in as a parameter to the method: 

class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}

The above code uses this keyword to differentiate between the local and class variables.