Java Scope in general
Why is it necessary to separate scopes of variables and methods? The fact is that sometimes programs are very large and it can be difficult to track one or another variable. In addition, in large projects, clear naming of variables is desirable so that it is clear what they are for. Scope specifically allows you to have different variables with the same name in different parts of the program. Such code is easier to maintain and read. Java scope defines where a certain variable or method is accessible in a program. Briefly:- A variable declared in a method is visible from the beginning of the declaration to the end of the method (method scope).
- A variable declared in a code block exists until the end of that code block.
- Variables that are method arguments exist till the end of the method.
- Class/object variables exist for the lifetime of the containing object. Their visibility is regulated by special access modifiers.
- Static class variables exist all the time the program is running. Their visibility is also determined by access modifiers.
Method Level Scope
Any variable declared in a method, including arguments, is not accessible outside of that method. All variables declared inside methods are visible from the beginning of their declaration to the end of the method. Here is an example of method variable scope:
public class JScopeTest1 {
public static void main(String[] args) {
System.out.println(myMethod(5));
System.out.println(myMethod(17));
}
public static int myMethod(int arg) {
int secondArg = 100; //local method variable
return secondArg + arg;
}
}
Here we have secondArg, a local variable or method argument. We can’t use this variable outside myMethod method or before it was declared.
If a variable is a function argument, then it is visible in the entire body of this method. In the example above we’ve got two such arguments: arg in myMethod and args in main method.
Class Level Scope
Class-Level Scope (Instance Variables) — any variable declared in a class is available for all methods of that class. Depending on its access modifier (i.e. public or private), it can sometimes be accessed outside of the class. So if a variable is a class variable, then it is bound to a specific object and exists as long as there is an object of this class. If there is no object, then there is no copy of the variable. The variable is visible from all methods of the class, regardless of whether they are declared before or after it. Each object has its own variable independent of other objects. Access to a variable from static methods is not possible.Code example
public class Student {
//class level variables
public String surname;
String name;
String secondName;
private Long birthday; // Long instead of long is used by Gson/Jackson json parsers and various orm databases
public Student(String surname, String name, String secondName, Date birthday ){
this.surname = surname;
this.name = name;
this.secondName = secondName;
this.birthday = birthday == null ? 0 : birthday.getTime();
}
@Override
public int hashCode(){
//TODO: check for nulls
//return surname.hashCode() ^ name.hashCode() ^ secondName.hashCode() ^ (birthday.hashCode());
return (surname + name + secondName + birthday).hashCode();
}
@Override
public boolean equals(Object other_) {
Student other = (Student)other_;
return (surname == null || surname.equals(other.surname) )
&& (name == null || name.equals(other.name))
&& (secondName == null || secondName.equals(other.secondName))
&& (birthday == null || birthday.equals(other.birthday));
}
}
Surname, name, secondName and birthday are Instance variables.
Block Scope
If a variable is defined/declared in some block of code, then it exists until the end of that block of code. Typically, such variables exist between the curly braces in which they are defined. Very often block scope could be a loop variable. A variable that is declared in a for loop condition is not accessible outside the loop, unless you defined it beforehand.
public class JScopeTest2 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int sum = 0;
sum = sum + i;
}
int sum = 1;
System.out.println(sum);
}
}
Both first sum and i variables are declared inside the loop and don’t exist outside this loop. However the second sum was declared outside the loop so this particular variable is going to be printed.
Static variables
If a variable is declared as static (marked with the static keyword), then it exists as long as its class exists. Typically, the JVM loads a class into memory on first use, when static variables are initialized.
import java.util.Date;
public class Student {
public static int today = 2022;
String surname;
String name;
String secondName;
Long birthday; // Long instead of long is used by Gson/Jackson json parsers and various orm databases
public Student(String surname, String name, String secondName, Date birthday ){
this.surname = surname;
this.name = name;
this.secondName = secondName;
this.birthday = birthday == null ? 0 : birthday.getTime();
}
public static void main(String[] args) {
System.out.println(today);
}
}
You shouldn’t create a new instance of Student class to use the static today variable. Here “2022” will be printed.
Access modifiers
Java has 4 access modifiers to restrict access to the method or variable. You can use them inside classes, not inside methods.private is the most restrictive modifier. It restricts access to methods and variables to the class they were declared. If there is no need to use certain methods or variables outside the class, use private. Class variables are usually private in Java.
If no access modifier is specified, the method or variable will accept the default modifier. default allows access only from the current package.
protected modifier allows access to a method or variable only from within the current package, unless it is accessed through a child class outside the package.
public is the least restrictive modifier. It allows you to access a class, method or variable not only from the class they are declared, but also from outside. This modifier is used really often.
GO TO FULL VERSION