Java Global vs. Local Variables

The Shortcut
2 min readJan 11, 2023

--

In Java, a variable can be declared as either a global variable or a local variable.

A global variable, also known as a class variable, is a variable that is declared outside of any method or block and is accessible to all methods and blocks within the class. These variables are defined at the class level and belong to the class, rather than any particular object.

A local variable, on the other hand, is a variable that is declared within a method or block and is only accessible within that method or block. These variables are defined within the scope of a method, constructor, or block and are not accessible from outside that scope.

Example of global variable

public class Example {
static int global_variable = 15;

public static void main(String[] args) {
int local_variable = 20;
// both global_variable and local_variable can be accessed here
}
public void method1() {
// global_variable can be accessed here
}
}

Example of local variable

public class Example {
public static void main(String[] args) {
int local_variable = 20;
// only local_variable can be accessed here
}
}

**note that a local variable does not take an access modifier (ex: public, private, protected, default) identifier whereas the global variable does.

It is good practice to keep the scope of variables as small as possible to minimize their potential for causing bugs and make the code more readable.

Find out more about Java here.

--

--

The Shortcut

Short on time? Get to the point with The Shortcut. Quick and concise summaries for busy readers on the go.