Introduction to Java Scope
In Java, scope defines where a variable can be accessed and how long it exists in the program. It tells the programmer which parts of the code can use a particular variable and for how long the variable will stay in memory.
We can write clean, safe, and error-free programs using scope, which also helps to avoid naming conflicts and prevent bugs caused by accidentally modifying the wrong variable.
Types of Variable Scopes in Java
There are four types of variable scopes in Java:
- Class Scope (Static Variables)
- Instance Scope (Instance Variables)
- Method Scope (Local Variables)
- Block Scope
1) Class Scope (Static Variables)
A static variable belongs to the class itself, not to any specific object. It is created when the class is loaded and destroyed when the program ends.
You can access it using the class name directly, without creating an object.
Example:
class Student {
static String schoolName = "Greenwood High"; // Class-scope variable
}
public class Main {
public static void main(String[] args) {
System.out.println(Student.schoolName); // Accessible directly through class name
}
}
- Here, schoolName has class scope, which means all Student objects will share the same value. If one object changes it, then all others see the updated value.
2) Instance Scope (Instance Variables)
An instance variable belongs to an object of a class. Each object gets its own copy of these variables. Variables declared without the static keyword are instance variables.
For example:
class Student {
String name; // Instance-scope variable
Student(String studentName) {
name = studentName;
}
void showName() {
System.out.println("Student Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
s1.showName(); // Output: Student Name: Alice
s2.showName(); // Output: Student Name: Bob
}
}
- Here, each student object has its own name. Changing one does not affect the other, because instance variables are tied to specific objects.
3) Method Scope (Local Variables)
Variables declared inside a method are called local variables. They are created when the method starts and destroyed when it ends.
For example:
class Calculator {
void addNumbers() {
int a = 5; // Local variable
int b = 10; // Local variable
System.out.println("Sum: " + (a + b));
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.addNumbers(); // Output: Sum: 15
}
}
- In this code, the variables a and b exist only inside the addNumbers() method. They cannot be accessed outside it, not even in another method of the same class.
4) Block Scope
A block refers to code written inside curly braces {}, like in loops, if statements, or methods.
For example:
public class Main {
public static void main(String[] args) {
if (true) {
int x = 20; // Block-scope variable
System.out.println("Inside block: " + x);
}
// System.out.println(x); //Error: x cannot be resolved outside the block
}
}
- Here, x exists only inside the if block. Once the block ends, x is destroyed and no longer accessible.
Scope and Shadowing In Java
In Java, shadowing happens when a local variable (like a method parameter) has the same name as an instance or class variable.
This can create confusion because Java will prioritize the local variable inside the method, and “hiding” the instance variable.
To solve this problem, we use the this keyword, which explicitly refers to the current object’s instance variable.
Example:
class Sample {
int number = 5; // Instance variable
public void updateNumber(int number) {
this.number = number; // 'this' distinguishes the instance variable from the local one
}
public void showNumber() {
System.out.println("Number: " + number);
}
}
public class Main {
public static void main(String[] args) {
Sample sample = new Sample();
sample.updateNumber(20);
sample.showNumber(); // Output: Number: 20
}
}
Explanation of this code:
- The instance variable number holds 5, and the method updateNumber takes a local parameter also named number.
- Using this.number, we update the instance variable instead of the local one.
- When we call showNumber(), it prints the updated instance variable 20.
Exercise For Students
Create a Java program that calculates the total score of a student based on marks from three subjects.
Use different types of variables (class-level, instance-level, and local variables) to practice scope. Then, print the following results:
- Total score.
- Average score.
- Maximum score among the three subjects.
Requirements:
- Use a class-level static variable to store the number of subjects.
- Use instance variables for each subject’s marks.
- Use local variables inside methods to calculate total, average, and maximum.
- Avoid variable shadowing errors by using this keyword where necessary.
Code example for your reference:
class Student {
static int numberOfSubjects = 3; // Class-level static variable
int subject1, subject2, subject3; // Instance variables
// Constructor to initialize marks
public Student(int subject1, int subject2, int subject3) {
this.subject1 = subject1;
this.subject2 = subject2;
this.subject3 = subject3;
}
// Method to calculate total
public int calculateTotal() {
int total = subject1 + subject2 + subject3; // Local variable
return total;
}
// Method to calculate average
public double calculateAverage() {
int total = calculateTotal();
double average = (double) total / numberOfSubjects; // Local variable
return average;
}
// Method to find maximum score
public int findMaximum() {
int max = subject1; // Local variable
if(subject2 > max) max = subject2;
if(subject3 > max) max = subject3;
return max;
}
}
public class ScopeExercise {
public static void main(String[] args) {
Student student = new Student(75, 88, 92);
int totalScore = student.calculateTotal();
double averageScore = student.calculateAverage();
int maxScore = student.findMaximum();
System.out.println("Total Score: " + totalScore);
System.out.println("Average Score: " + averageScore);
System.out.println("Maximum Score: " + maxScore);
}
}
Expected Output:
Total Score: 255
Average Score: 85.0
Maximum Score: 92
- Try to understand this code by yourself and write your logic on the Java scope.