Java Variable Scope

This article discusses the concept of Variable Scope in Java.

Before we get into Variable scope, you need to understand the concept of Java code blocks. A code block begins with an opening curly bracket ({) and closes with a closing curly bracket (}). Each Block creates its own personal scope. Creating multiple blocks will result in multiple scopes. Below are some examples of code blocks and there respective scopes.

The most commonly used variable scope in Java, the area between the opening and closing brackets of the main() method.

public class example {			
	public static void main(String[] args) 	{	
              // Instructions
	}
}

The for loop code block.

for (int x = 0; x < 10; x++) {
        // Instructions to be executed
}

Now, Java allows you to declare variables within any code block. This results in variables being declared in different scopes. Variables declared in a scope, cannot be accessed by code outside that scope. See the below example where we create a custom code block with the name block.

public class example {			
	public static void main(String[] args) 	{	
              block: {
                   int y = 5;
              }
              System.out.println(y);         
 	}
}

Now, if it was possible for us to access the variable y from the main() scope, we would see 5 printed to screen. However, due to the concept of encapsulation (Part of object oriented programming) , y is not visible (accessible) to anything out of the block scope (also referred to as local scope). As a result, the following error is thrown.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	y cannot be resolved to a variable

You might wonder, why can the block code block access variables in main()‘s local scope? Like the example shown below.

public class example {			
	public static void main(String[] args) 	{
              int y = 5;	
              block {
                     System.out.println(y);
              }                   
 	}
}

This is because the main() method only prevents a variable being accessed from outside the local scope. If look at the above example, you’ll realize that the block scope is actually within the main() scope. You may think of it as Child scope. The child can take from the parent, but the parent cannot take from the child.

To summarize, a code block within an another code block can access variables from it’s parent block. However, the parent block cannot access the child block.


Variable Scope in Methods

Let’s look at the variable scope in Java methods.

Each Java method has it’s own local scope. Since methods exist apart from the rest of the code, it’s variables can’t be accessed (normally). There is another side effect of this. Since the variables in a method aren’t visible to anyone else, you may create a variable with the same name. Although I don’t recommend doing this anyway to avoid any confusion.

See the below example which demonstrates the effect of different local scopes on variable names.

public class example {
	
	int add(int x, int y) {
		return x + y;
	}
	
	int inc(int x) {
		return x + 1;
	}
	
	public static void main(String[] args) {		
		String x = "Hello";
	}
}

There are three different variables here, with different values and purposes and even different data types, yet they have the same name “x“. No error is thrown because

Minimizing Scope

In general, when declaring any variable or constant, it’s good practice to keep the scope as narrow as possible (block scope is the narrowest). This helps conserve memory resources and minimizes the chances of your code referring to the wrong variable by accident.


This marks the end of the Java Variable Scope article. Any suggestions or contributions for CodersLegacy are more than welcome. You can ask any relevant questions in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments