Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Scope

Scope is the part of a program where a variable can be used by name. In Java it is defined by curly braces: a variable lives from its declaration to the end of the block it is declared in.

Local variables

A variable declared inside a method is called local. It is visible only in that method, and other methods cannot reach it:

void main() {
    String message = "Hello";
    IO.println(message);
    printTwice();
}
 
void printTwice() {
    String message = "Bye";
    IO.println(message + " " + message);
}

Output:

Hello
Bye Bye

The two message variables are unrelated: each belongs to its own method. Method parameters are local variables too.

Blocks

A variable declared inside an if block or a loop disappears after the closing brace. If you need the value after the block, declare the variable before it:

void main() {
    int age = 20;
    String status;
 
    if (age >= 18) {
        String note = "adult";
        status = note;
    } else {
        status = "minor";
    }
 
    IO.println(status);
}

Output:

adult

note no longer exists outside the if block, while status is declared outside and stays available.

Loop variables

A counter declared in a for header is visible only inside the loop. That is why neighboring loops can reuse the name i:

void main() {
    for (int i = 0; i < 2; i++) {
        IO.print("A" + i + " ");
    }
    for (int i = 0; i < 2; i++) {
        IO.print("B" + i + " ");
    }
    IO.println();
}

Output:

A0 A1 B0 B1

Program fields

A variable declared outside all methods is called a field. Every method in the file can see it, and it keeps its value between calls:

int visits = 0;
 
void visit() {
    visits++;
}
 
void main() {
    visit();
    visit();
    visit();
    IO.println("Visits: " + visits);
}

Output:

Visits: 3

Fields are convenient, but any method can change them, which makes them harder to keep track of. If only one method needs the data, make the variable local.

Shadowing

If a local variable has the same name as a field, it shadows the field inside the method: the name refers to the local one. To reach the field, use this.:

String name = "Field";
 
void main() {
    String name = "Local";
    IO.println(name);
    IO.println(this.name);
}

Output:

Local
Field

The word this means the current object — more on it in the OOP chapter.

Common mistake

A variable declared inside a block is not visible after it. The compiler says it cannot find the name:

void main() {
    for (int i = 0; i < 3; i++) {
        int square = i * i;
    }
    IO.println(square);
}

Output:

Main.java:5: error: cannot find symbol
    IO.println(square);
               ^
  symbol:   variable square
  location: class Main
1 error
error: compilation failed

Declare the variable before the loop and only assign it inside.

Thanks for reading!

Donate to the site — we work hard for you.