Java Variable Scope: What is variable scope in Java? (Explained)

In this Java tutorial, we will learn What is variable scope? What are the scopes in Java? How to manage variables scope along with Simple examples for better understanding. So, Let’s get started –

Learn about the Java Variable Scope with Examples


Java Variable Scope : What is variable scope?

Variables play an important role in any programming language. Before jumping to the Java variable scope, let’s first recall some important points about variable –

Points to Remember about Java Variable :

1) When we use a variable, we give some name to a memory storage (or memory block) that our program/application can use later.

2) In Java, variables must be declared before their use.

3) Java is a Strictly Typed Language, which means, every variable must be of some type (such as Integer, Character, float or other).

4) Strictness does not allow us to perform any irregular operations (such as Multiplication) on variables of different types (such as between an Integer and a String).

 

It raises some Questions –

A) Till when, a Variable will hold its value?

B) Till which line of code, One can access the variable?

At it’s core, the above questions are targeting the Scope of a variable and a Generic answer to these question is by using Curly Braces {}

In Java, the Curly Braces { } define the life of a variable and the scope as well. Also, Till where, that variable would be accessible. Here is a simple example that explains the Java variable scope –

 

Example 1 : Java Variable Scope

{                      // A Scope created in memory, Assume- its name is "OuterScopeA"

    int x = -3;        // Declaring a variable 'x' and initializing with integer value '-3'
    double y = 8;      // Declaring a variable 'y' and initializing with integer value '8'

    {                  // Opened a curly brace, Created a Scope, Let's say 'InnerScopeA'

        x = 50;        // Accessing and updating the variable 'x'
        y = 200;       // Accessing and updating the variable 'y'
        char c = 'A';  // Declaring a variable 'c' and initializing with character value 'A'

    }                  // Closed the curly brace, 'InnerScopeA' closed

    System.out.println(x + "  " + y); // It will Print:  50  200.0
    System.out.println(c);            // Its a Compile time error, because variable 'c' is Out of Scope

    {                  // Opened a curly brace, Created aother Scope, Let's say 'InnerScopeB'
        c = 'B';       // Compile time error and out of scope
    }                  // InnerScopeB closed

}                      // OuterScopeA closed

 

Explaination :

In the very first line of above Java scope variable example, A Scope created in Memory. Let’s give some name to this scope, say “OuterScopeA”.

Next, we declared a variable x and initialized x with an integer value -3. After that, we declared another variable y and initialized that with an integer value 8.

Here, an important point to remember is, all the Inner-scopes of any Method can easily access the variables defined in Outer Scope.

Then, we created 2 Scopes: “InnerScopeA” and “InnerScopeB” using the Curly braces { } (check the comments for reference) and, When the “InnerScopeB” tried to access the variable c declared in “InnerScopeA”, the Java compiler threw an Error :

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

 

If you’re also getting these Errors in your machine after running the above code snippet, then just put the above example inside the curly braces of your main(){} method and try to compile it.

Both of the c cannot be … errors are generated because of illegal use of Java variable Scope. And, To fix these Scope related errors, just shift the char c = ‘A’; statement to its parent scope { } and put the statement below the declaration of variable y.


Example 2: With try-catch

Here’s another example, that explains how scope works –

try
{
    YourObject someObject = new YourObject();     // Object Created
    someObject.riskyMethod();                                   // Accessing Object
}
catch(Exception e)
{
    // Handle the exception
}
someObject.someNonRiskyMethod();                    // Compile-Time Error : Accessing object out-of-scope

 

Explaination :

In the above example, when someone tries to access someObject out to try block, the compiler throws an error. It’s because, someObject was declared in local scope – the try block. And, a Possible Solution would be –

YourObject someObject = new YourObject();   // Outer Scope
try
{
    someObject.riskyMethod();                               // Inner Scope
}
catch(Exception e)
{
    // Handle the exception
}
someObject.someNonRiskyMethod();                // Accessing someObject in Outer Scope

Wrap Up 

So far, we have learned- What is variable scope in Java? We have also seen some examples focused on Java variable scope and try-catch.

I hope, this article helped you to learn a bit more about- Variable Scope in Java? If you have any doubt, query or suggestions, then drop a comment or send me a direct email via Google, and I’ll try my best to give you the solution within a day.

Also, Rate this article on Facebook and, Don’t forget to check Other Useful Java Articles that you may like :

Read Next :

Leave a Comment