Scope of Variables in Java Tutorial

Drag to rearrange sections
Rich Text Content

In this tutorial, we will learn what the scope of variables are and how they work in Java.

Definition of Scope: What Does Scope Mean?

Depending on the places where we declare a variable, it’ll have some level of accessibility and this is called the scope of that variable.

For example, if we declare a variable in a method, the scope of the variable will be Method Scope. This means we can only access the variable in the method and no other methods can see or access the value of this variable or change it.

Scopes of variables in Java

In short, a variable can have any of these three scopes:

  • Class scope (AKA member variable)
  • Method scope (AKA local variable)
  • Block scope
  • Java Class Scope (AKA member variable)

A variable that is declared outside of any method in a class has the Class Scope.

This means methods in that class can access and change the content of the variable if they want.

Note: We can’t have a variable with the same name declared twice in Class Scope.

Example: class scope variable in Java

Create a file named `Person` and put the class `Person` you see below into the file:

public class Person {
    private String name;
    private String lastName;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Now create another file named `Simple` and put the code below into that file:

public class Simple {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        person.setLastName("Doe");
        System.out.println(person.getName());
        System.out.println(person.getLastName());
    }
}

Output:

John

Doe

Inside the `Person` class, methods like `getName()` and `getLastName()` return the value of the `name` and `lastName` variables, respectively.

These two variables are declared inside the class as the attribute of that class. And so they have the scope of the class and that means not just the two methods mentioned above, but also any other method in this class can access these two variables.

Java Method scope (AKA local variable)

A variable that is declared in the body of a method has Method Scope. This means the variable is only accessible within the body of the method and no other method has the access to that variable.

The beauty of such a variable is that because a method scope variable is not in the scope of other methods, other methods can also have their own variable with the same name and type.

Method Scope Notes:

  • In the same method, we can’t have a variable with the same name declared twice!
  • But we can have two variables with the same name, but one is class scope, and the other is Method scope. In such case the Method scope variable will shadow the Class scope variable. (Later in this section, we explain what shadowing means in practice)
  • Also, two independent methods can have a variable with the same name! This is because the scope of each variable will be separate from the other.

Example: method scope variable in Java

public class Simple {
    public static void main(String[] args) {
        int age = 100;
        printAge();
    }
    public static void printAge(){
        System.out.println(age);
    }
}

If we try to compile this program, we will get a compile time error because the variable `age` is declared inside the body of the `main` method so it has the scope of method but we’re trying to get the value of this variable inside the `printAge()` method!

Java Block scope (AKA bracket scope)

A variable that is declared inside a block `{}` like in an `if` statement is only accessible within that block.

This means after the closing brace `}` of that block, the variable does not exist anymore.

Example: Block scope variable in Java

public class Simple {
    public static void main(String[] args) {
        for (int test = 0; test<10; test++){
            System.out.print(test+", ");
        }
        System.out.println("The final value of the 'test' variable is: "+ test);
    }
}

Output:

Error:(8, 75) java: cannot find symbol

symbol: variable test

location: class tuto.Simple

In this example, we’ve created the variable `test` inside the body of the `for` loop. Because this variable is Block Scope, it is only accessible within the body of the `for` loop.

After the body of the loop and outside the block, we tried to access the value of the `test` variable and because of that we got the compile time error.

Shadowing variables in Java:

Let’s say we have a variable with the name `age` and with the scope of class. Also, we have another variable with the same name but the scope of Method.

This second variable is declared inside a method called `print`.

Now, if we call the `print` method and want to get the value of the `age` variable, what value do you think will be sent to the output stream?

It’s the value of the Method Scope variable.

Basically, when we call a variable inside a method, the compiler will first check the method where the call happened in there and look for a variable with this name. If in the method, it finds such a variable, then it’ll choose its value. Otherwise, the compiler will look one level higher, which is the variables with Class Scope, and see if there is a variable with this name.

At the end if the compiler can’t find such a variable with this name, it’ll send an error.

Example: Shadowing variable in Java

public class Simple {
    private static int age = 80; 
    public static void main(String[] args) {
        int age = 100;
        System.out.println("The age is: "+ age);
    }
}

Output: The age is: 100

Here there’s variable named `age` with the class scope and another variable with the same name inside the body of the `main` method, which means its scope is Method.

When we called the println () method to get the value of the `age` variable, the compiler chooses the value of the one with Method scope and sent its value to the output stream. This is because the Java engine is in the current scope (scope of the `main` method) and here it finds a variable with the name `age` and so it won’t go to the higher scope (global in this case) to find the variable.

More to Read

If you liked this tutorial and want to learn more, you can check the EnjoyTutorials.com where we explained at ease, the core of programming languages like Java, Python, and many more...

rich_text    
Drag to rearrange sections
Rich Text Content
rich_text    

Page Comments