Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In Java, as in any programming language, each variable has a scope. This is the segment of the program where a variable can be used and is valid.

In this tutorial, we’ll introduce the available scopes in Java and discuss the differences between them.

2. Class Scope

Each variable declared inside of a class’s brackets ( {} ) with private access modifier but outside of any method, has class scope. As a result, these variables can be used everywhere in the class, but not outside of it:

public class ClassScopeExample {
    private Integer amount = 0;
    public void exampleMethod() {
        amount++;
    }
    public void anotherExampleMethod() {
        Integer anotherAmount = amount + 4;
    }
}

We can see that ClassScopeExample has a class variable amount that can be accessed within the class’s methods.

If we don’t use private, it will be accessible from the entire package. Check access modifiers article for additional information.

3. Method Scope

When a variable is declared inside a method, it has method scope and it will only be valid inside the same method:

public class MethodScopeExample {
    public void methodA() {
        Integer area = 2;
    }
    public void methodB() {
        // compiler error, area cannot be resolved to a variable
        area = area + 2;
    }
}

In methodA, we created a method variable called area. For that reason, we can use area inside methodA, but we can’t use it anywhere else.

4. Loop Scope

If we declare a variable inside a loop, it will have a loop scope and will only be available inside the loop:

public class LoopScopeExample {
    List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
    public void iterationOfNames() {
        String allNames = "";
        for (String name : listOfNames) {
            allNames = allNames + " " + name;
        }
        // compiler error, name cannot be resolved to a variable
        String lastNameUsed = name;
    }
}

We can see that method iterationOfNames has a method variable called name. This variable can be used only inside the loop and is not valid outside of it.

5. Bracket Scope

We can define additional scopes anywhere using brackets ({}):

public class BracketScopeExample {    
    public void mathOperationExample() {
        Integer sum = 0;
        {
            Integer number = 2;
            sum = sum + number;
        }
        // compiler error, number cannot be solved as a variable
        number++;
    }
}

The variable number is only valid within the brackets.

6. Scopes and Variable Shadowing

Imagine that we have a class variable, and we want to declare a method variable with the same name:

public class NestedScopesExample {
    String title = "Baeldung";
    public void printTitle() {
        System.out.println(title);
        String title = "John Doe";
        System.out.println(title);
    }
}

The first time that we are printing title, it will print “Baeldung”. After that, declare a method variable with the same name and assign to it the value “John Doe“.

The title method variable overrides the possibility to access to the class variable title again. That’s why the second time, it will print “John Doe“.

Confusing, right? This is called variable shadowing and isn’t a good practice. It’s better to use the prefix this in order to access the title class variable, like this.title.

7. Conclusion

We learned the different scopes that exist in Java.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW