Types of scope
Instance variable scope
java
public class Student {
private String name; // accessible in ALL methods below
private double gpa;
public Student(String name, double gpa) {
this.name = name; // can access name here
this.gpa = gpa;
}
public String getName() {
return name; // can access name here
}
public boolean isHonors() {
return gpa >= 3.5; // can access gpa here
}
}
Local variable scope
java
public class Example {
public void method1() {
int x = 10; // x exists only in method1
System.out.println(x);
}
public void method2() {
// System.out.println(x); // COMPILE ERROR — x doesn't exist here
int y = 20; // y exists only in method2
}
}
Parameter scope
java
public void setAge(int age) {
this.age = age; // parameter age exists here
}
public void printInfo() {
// System.out.println(age); // This refers to instance variable, not the parameter!
}
Block scope (loop and if variables)
java
public void demo() {
// Loop variable — only exists inside the loop
for (int i = 0; i < 10; i++) {
int doubled = i * 2; // only exists inside loop body
System.out.println(doubled);
}
// i is gone here
// doubled is gone here
// If block variable
if (true) {
int temp = 42;
System.out.println(temp); // works
}
// temp is gone here
}
Shadowing — when names collide
java
public class Point {
private int x = 10;
public void setX(int x) {
// x here refers to the PARAMETER, not the instance variable
System.out.println(x); // parameter
System.out.println(this.x); // instance variable
this.x = x; // set instance var to parameter
}
}
Point p = new Point();
p.setX(5);
// prints: 5 (parameter)
// 10 (instance variable, before assignment)
Static variables and methods
java
public class Student {
private String name;
private static int count = 0; // shared by ALL Student objects
public Student(String name) {
this.name = name;
count++; // increment every time a new Student is created
}
// Static method — belongs to the class
public static int getCount() {
return count;
}
// Instance method — belongs to an object
public String getName() {
return name;
}
}
System.out.println(Student.getCount()); // 0
Student s1 = new Student("Alice"); // count = 1
Student s2 = new Student("Bob"); // count = 2
System.out.println(Student.getCount()); // 2
Static vs. instance
java
// Static method CANNOT access instance variables:
public static int getCount() {
// return name; // COMPILE ERROR — name is instance variable
return count; // works — count is static
}
// Instance method CAN access both:
public String getInfo() {
return name + " (#" + count + ")"; // both work
}
Scope trace practice
java
public class ScopeDemo {
private int x = 1;
public int method(int x) {
// Parameter x shadows instance variable x
int y = x + this.x; // parameter + instance var
for (int i = 0; i < 3; i++) {
y += i;
}
return y;
}
}
ScopeDemo demo = new ScopeDemo();
int result = demo.method(5);
AP Exam Tips
- •
- •
- •
- •
- •
Common Mistakes
- •
- •
- •
- •
- •