Scope determines where a variable can be accessed. Understanding scope helps you reason about variables inside and outside methods.
Local variables
Variables defined inside a method are local variables. They can only be accessed inside that method.
static void swap(int a, int b) {
int temporary = a;
a = b;
b = temporary;
System.out.println("inside swap(): " + a + " " + b);
}
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println("Before: " + a + " " + b);
swap(a, b);
System.out.println("After: " + a + " " + b);
}Output:
Before: 1 2
inside swap(): 2 1
After: 1 2Two rooms, two pairs of boxes
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
static variables
A local variable exists only inside its method. When several static methods need to read and update the same value, declare the variable outside those methods and mark it static.
A static variable has one value for the duration of the program. After one static method changes it, another static method reads the updated value.
static int score = 0;
static void addScore(int points) {
score += points;
}
static int getScore() {
return score;
}
public static void main(String[] args) {
addScore(10);
addScore(5);
System.out.println(getScore());
}Output:
15Use a static variable for state maintained by several static methods. Prefer focused methods for updates instead of assigning to it from arbitrary locations.
KNOWLEDGE QUIZ
Build a shared scoreboard
Store a score in one static variable and use two focused static methods to update and read it.
- Declare static int score and initialize it to 0.
- Write addScore(int points).
- Write getScore() and verify the result in main().