Table of Contents
Introduction
In Java, static or instance variables are available throughout a class. Therefore we cannot have 2 static and/or instance variables with the same name. Similarly, you cannot have two variables inside of a method that share the same name, whether they are input parameters or local variables to the method. However, when you cross the boundary between static/instance variables and input parameter/local variables for a method, you can make a method use a shadowed (duplicated) variable name.
Method Input Parameters
In Java, even if we have a variable name already defined at the instance or class level, it is valid to have the same variable name as an input parameter to a method. For example:
public class Babysitter {
private String name = "Kristy";
public void printInfo(final String name) {
System.out.println(name);
}
public static void main (String[] args) {
Babysitter babysitter = new Babysitter();
babysitter.printInfo("Julia");
}
}
If we were to run the main method above, the output would be “Julia”. Although “Kristy” is set as the name instance variable’s value when the Babysitter object is created, the printInfo’s name parameter shadows the instance variable and it is what is used when System.out.println is invoked.
Local Variables
The same is true inside of a method, if a local variable with the same name is declared:
public class Babysitter {
private String name = "Ashley";
public void printInfo() {
String name = "Nora";
System.out.println(name);
}
public static void main (String[] args) {
Babysitter babysitter = new Babysitter();
babysitter.printInfo();
}
}
Here again, if we run this code, “Nora” from the local variable inside of the method will be printed, rather than “Ashley” from the instance variable. The local variable again shadows the instance variable, making direct variable name references point to the more-immediately scoped variable.
Style Checkers
Some style checkers will help avoid such possibly confusing scenarios. For example, the maven-checkstyle-plugin‘s checkstyle checks include:
Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
https://checkstyle.org/checks/coding/hiddenfield.html#HiddenField
See a prior post: Style Matters! Adding a Checkstyle Build Breaker (Quality Gate) for details on adding that style checker to your Maven build.
Summary
Although the Java compiler does help ensure that two variables with the same name are not declared in either static/instance variable scoping or within a method’s input parameters & local variables, it doesn’t prevent shadowing of variable names as we cross between method and instance/class scoping. Style checkers can help avoid confusing situations where we overlook that a variable shadowing is occurring and help us avoid sometimes difficult-to-diagnose bugs. In a future post, we will discuss how we can still access a shadowed static / instance variable, if desired.

Leave a comment