Sub topic 9
Where a variable is visible
This chapter assumes you can declare variables and know the primitive and collection types from earlier chapters. It covers the region of code where a name can be used (its scope), how long its value lives (its lifetime), and the compile errors you get when you get either wrong.
Block scope
A local variable is visible from its declaration to the closing brace of the block that contains it. A block is any code between { and }: a method body, an if branch, a loop body, a try section, or a catch section.
Integer total = 0;
for (Integer i = 0; i < 3; i++) {
Integer square = i * i;
total += square;
}
System.debug(total);
// System.debug(square); // compile error: Variable does not exist: square
// System.debug(i); // compile error: i is scoped to the loopsquare exists only inside the loop body. The loop counter i exists only for the loop. Only total is visible after the loop ends.
A variable is also not visible before the line that declares it. Using a name above its declaration fails with Variable does not exist.
No shadowing of locals
Apex does not let an inner block redeclare a local variable that an enclosing block already declared. This differs from Java-style languages that allow some shadowing in nested scopes, and from JavaScript, where an inner let hides an outer one.
Integer count = 1;
if (count > 0) {
// Integer count = 2; // compile error: Duplicate variable: count
count = 2;
}
System.debug(count);Method parameters follow the same rule. A parameter is a local variable of the method body, so you cannot declare a local with the same name.
Two blocks that are siblings, not nested, can reuse a name because neither is inside the other.
for (Integer i = 0; i < 2; i++) {
String label = 'first ' + i;
System.debug(label);
}
for (Integer i = 0; i < 2; i++) {
String label = 'second ' + i;
System.debug(label);
}try, catch, and finally have separate scopes
A variable declared inside try is not visible in catch or finally. If you need a value after the whole statement, declare the variable before the try.
Integer divisor = 0;
Integer result;
try {
result = 10 / divisor;
} catch (MathException e) {
result = -1;
}
System.debug(result);This prints -1. The exception variable e is visible only inside its catch block.
Class-level variables
Variables declared in a class but outside any method are member variables. They come in two kinds.
- An instance variable belongs to one object. Each
newcreates its own copy. - A static variable belongs to the class. Every object and static method in the same transaction shares one copy.
public class Counter {
private static Integer created = 0;
private Integer count = 0;
private String name;
public Counter(String name) {
this.name = name;
created++;
}
public void increment() {
count++;
}
public Integer getCount() {
return count;
}
public static Integer getCreated() {
return created;
}
}Run this in Anonymous Apex after saving the class:
Counter a = new Counter('a');
Counter b = new Counter('b');
a.increment();
a.increment();
b.increment();
System.debug(a.getCount());
System.debug(b.getCount());
System.debug(Counter.getCreated());The output is 2, 1, and 2. Each object has its own count, and created is shared.
In the constructor, the parameter name hides the member name. Apex allows this for member variables, and this.name reaches the member. A static method has no object, so it cannot read count or use this. Doing so is a compile error.
Lifetime
Scope is about where code can see a name. Lifetime is about how long the value exists.
| Kind | Declared | Visible to | Lives until |
|---|---|---|---|
| Local variable | Inside a method or block | The rest of that block | The block ends |
| Method parameter | In the method signature | The whole method body | The method returns |
| Instance variable | In the class body | Instance methods of that object | The object is garbage collected |
| Static variable | In the class body with `static` | Every method of the class, plus other code if public | The end of the transaction |
Static variables reset every transaction
A static variable keeps its value only for the current transaction. Another user's request, or your next request, starts with fresh values. A common use is a guard that stops a trigger from running its logic twice in one transaction.
public class RunGuard {
private static Boolean hasRun = false;
public static Boolean shouldRun() {
if (hasRun) {
return false;
}
hasRun = true;
return true;
}
}System.debug(RunGuard.shouldRun());
System.debug(RunGuard.shouldRun());The first call prints true and the second prints false.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Variable does not exist: x` | Used outside its block, or before its declaration | Declare it in an enclosing block, above the first use |
| `Duplicate variable: x` | Redeclared in a nested block or with a parameter's name | Reuse the existing variable or rename the new one |
| Value is `null` after `try` | Assigned only inside `try`, and the exception skipped the assignment | Declare before `try` and set a default in `catch` |
| Static value "forgot" its data | A new transaction started | Pass the data in, or query it again |
| Static method cannot see a field | The field is an instance variable | Make the field static, or call an instance method on an object |
Choosing the narrowest scope
Declare each variable in the smallest block that needs it. A narrow scope makes reads easier and prevents a later edit from using a stale value. Use an instance variable only when the value must outlive a single method call on the same object. Use a static variable only when the data must be shared across the whole transaction, as in the recursion guard.
Exercise
This code fails to compile. Name the problem and fix it so System.debug prints 5.
Integer n = 2;
if (n > 1) {
Integer total = n + 3;
}
System.debug(total);
Show answer
total is declared inside the if block, so it is not visible after the closing brace. Declare it before the if: Integer total = 0; if (n > 1) { total = n + 3; } System.debug(total); This prints 5.
Exercise
A class has private static Integer created = 0; and private Integer count = 0;. Two objects are created, and each calls increment() (which does count++) once. What are count for each object and created for the class, and why?
Show answer
Each object's count is 1, because instance variables are separate per object. created is shared by the class, so after two constructors each did created++, it is 2.
Exercise
Why does the following line inside a for body fail with a duplicate variable error when the method already declared Integer i earlier at method level?
for (Integer i = 0; i < 3; i++) { }
Show answer
Apex does not allow an inner block to redeclare a local variable that an enclosing block already declared. The method-level i is still in scope inside the loop, so the loop's i is a duplicate. Rename one of them, or declare the method-level i only inside a block that ends before the loop.