Loading...

Variable Scope in Java

A Simple Thought

Imagine you’re in a classroom. You can talk to your classmate sitting next to you, but you can’t talk to someone in another classroom unless you step out.
In programming, variables work in a similar way, each variable has a scope, meaning the part of the program where it can be seen or used.

In this lesson, you will learn what variable scope means, how it works, and how to avoid common mistakes when variables are used in different places.

The Project: Bank Account Balance

You will create a small program that simulates a simple bank balance check.
It will have one variable that belongs to the main method, and another inside a custom method.
You’ll see how these variables behave differently depending on where they are declared.

Here’s how your output should look:

text
5 lines
|
31/ 500 tokens
1
2
3
4
5
========================
   BANK ACCOUNT CHECK
   Current Balance: 5000
   Updated Balance: 6000
========================

The first balance is printed inside the main method, and the updated balance comes from another method.

The Concept: Variable Scope

The scope of a variable refers to where in the program the variable is visible or accessible.
There are two main kinds of scope in Java:

  1. Local Scope: A variable declared inside a method can only be used inside that method. Once the method ends, the variable disappears.
  2. Global Scope (Class-Level): A variable declared outside all methods but inside the class can be used by any method in that class.

Here’s a simple example:

java
9 lines
|
64/ 500 tokens
1
2
3
4
5
6
7
8
9
public class Example {
    static int globalNumber = 10; // global scope

    public static void main(String[] args) {
        int localNumber = 5; // local scope
        System.out.println(globalNumber);
        System.out.println(localNumber);
    }
}
Code Tools

The globalNumber can be accessed anywhere in the class, but localNumber only works inside the main method.

Why This Matters

Scope helps you control where data can be changed or used.
Without scope rules, variables could accidentally overwrite each other, causing errors or unexpected results.

Think of scope as keeping your program organized and protected, just like different rooms in a house. Each room has its own things, and you can’t use them unless you are inside that room.

Let’s Build the Bank Account Program

Here’s the complete program:

java
18 lines
|
139/ 500 tokens
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BankAccount {
    static int balance = 5000; // global variable

    public static void main(String[] args) {
        System.out.println("========================");
        System.out.println("   BANK ACCOUNT CHECK");
        System.out.println("   Current Balance: " + balance);

        updateBalance();

        System.out.println("========================");
    }

    public static void updateBalance() {
        int newBalance = balance + 1000; // local variable
        System.out.println("   Updated Balance: " + newBalance);
    }
}
Code Tools

When you run this, the main method can see and print balance, but only the updateBalance method can see the newBalance variable.
If you try to print newBalance from the main method, Java will show an error because its scope is limited.

How It Works

  1. The variable balance is declared outside all methods, so both methods can access it.
  2. The variable newBalance is declared inside the updateBalance method, so it exists only there.
  3. When updateBalance finishes running, newBalance is removed from memory.
  4. The main method can still use balance because it is globally accessible.

This difference in visibility between variables is what scope controls.

Learn Together with AI

If you are using an AI Copilot, you can explore variable scope by asking it to create small experiments.

Try this prompt:
“Write a Java program that shows the difference between a global and a local variable.”

Then try these follow-up prompts:

  • “Show what happens if two variables have the same name in different scopes.”
  • “Make a program where one method changes a global variable.”
  • “Explain what happens when a variable is declared inside an if-statement.”

These variations help you understand how scope affects what parts of the program can see and change a variable.

Practice Challenge

Create a program that tracks a player’s score in a game.
There should be one global variable for the total score and a local variable for the score earned in the current round.
The output should look like this:

text
6 lines
|
32/ 500 tokens
1
2
3
4
5
6
========================
   GAME SCORE TRACKER
   Total Score: 200
   Round Score: 50
   New Total: 250
========================

Example Solution

java
21 lines
|
151/ 500 tokens
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class GameScore {
    static int totalScore = 200;

    public static void main(String[] args) {
        System.out.println("========================");
        System.out.println("   GAME SCORE TRACKER");
        System.out.println("   Total Score: " + totalScore);

        updateScore();

        System.out.println("========================");
    }

    public static void updateScore() {
        int roundScore = 50;
        int newTotal = totalScore + roundScore;

        System.out.println("   Round Score: " + roundScore);
        System.out.println("   New Total: " + newTotal);
    }
}
Code Tools

When you run this program, you’ll see how global and local variables work together but stay in their own areas.
If you try to access roundScore from outside updateScore, Java will not allow it because of scope limits.

Coming Up Next

You now understand how variable scope defines where data can live and be used.
Next, you will explore a key concept in Java, classes and objects.
You will learn how to create your own data types and bring structure to your programs.