2.1 Variable Scope & Java Class Structure
Key Takeaways
Local variables declared in a block are in scope from their own initializer through the end of that block, have no default values, and must be definitely assigned before they are read
Instance fields belong to each object, static (class) fields belong to the class itself, and both receive default values when not explicitly initialized
A local variable or parameter can shadow a class field (resolved with this.field or ClassName.field), whereas declaring a duplicate local variable name inside a nested block fails to compile
A .java source file must follow strict element order—optional package first, optional imports second, type declarations third—while comments may appear anywhere
At most one top-level type in a .java file may be public, and its exact name must match the filename; in Java SE 8 a single underscore _ compiles with a warning, whereas const and goto are reserved keywords
Variable Scope & Java Class Structure
Many questions on the Oracle Java SE 8 Programmer I (1Z0-808) exam test whether a short snippet compiles, fails to compile, or prints an unexpected value because a variable went out of scope or shadowed a field. Mastering variable scope and source file structure lets you spot those traps in seconds.
Three Kinds of Variable Scope
Java classifies variables by where they are declared, which directly determines their scope (where the name is visible), lifetime (how long the value stays in memory), and default initialization.
| Variable Kind | Where Declared | Scope | Default Value? |
|---|---|---|---|
| Local variable | Inside a method, constructor, initializer block, or for-loop header | For a block local, from its own initializer through the block’s closing brace. A loop-header variable follows the scope rules of its loop. | No (must be assigned before read) |
| Method / constructor parameter | Parameter list of a method or constructor | Entire body of that method or constructor | No (receives caller's argument) |
| Instance variable (field) | Inside a class body, outside methods/blocks, without static | Entire class; accessible via an instance from static contexts | Yes (0, 0.0, false, \u0000, null) |
Class (static) variable | Inside a class body, outside methods/blocks, with static | Entire class (and externally via ClassName.field if visible) | Yes (0, 0.0, false, \u0000, null) |
Warning
An ordinary local variable can be declared without an initializer. Reading it requires definite assignment. Blank final variables also have rules about where a later assignment is legal.
Consider how each scope behaves in a single class:
public class ScopeLedger {
static int globalCount; // class scope, defaults to 0
private double balance; // instance scope, defaults to 0.0
public void applyFee(boolean waive) {
double fee; // local variable, NO default value
if (waive) {
fee = 0.0;
} else {
fee = 2.50;
}
// Compiles: both branches guarantee 'fee' is initialized
balance -= fee;
for (int step = 0; step < 2; step++) {
int temp = step * 10;
globalCount += temp;
}
// System.out.println(step); // Does NOT compile: 'step' out of scope
// System.out.println(temp); // Does NOT compile: 'temp' out of scope
}
}
Notice two common 1Z0-808 traps demonstrated above:
- Conditional initialization: If the
elsebranch were omitted,balance -= fee;would fail withvariable fee might not have been initialized, even if you mentally tracewaiveastrueat runtime. The compiler checks definite assignment statically. for-loop header scope: A variable declared in aforheader (int step = 0) is scoped to theforstatement only. Referencingstepimmediately after the loop's closing brace fails to compile.
Variable Shadowing vs. Illegal Duplicate Locals
Java allows a local variable or parameter to share the name of an instance or static field—a pattern called shadowing. Inside that method or block, the simple name refers to the local variable, hiding the field. To reach the shadowed field, qualify it with this.fieldName (for instance fields) or ClassName.fieldName (for static fields).
However, Java forbids declaring a local variable in an inner block with the same name as a local variable or parameter already in scope in the same method or constructor.
public class ShadowDemo {
int level = 10; // instance field
static String tag = "A"; // static field
public void inspect(int level) { // shadows instance field 'level'
String tag = "local"; // shadows static field 'tag'
System.out.println(level); // prints parameter 'level'
System.out.println(this.level); // prints 10 (instance field)
System.out.println(tag); // prints "local"
System.out.println(ShadowDemo.tag); // prints "A" (static field)
if (level > 0) {
// int level = 99; // Does NOT compile! Duplicate local/parameter
// String tag = "B"; // Does NOT compile! 'tag' still in scope
int bonus = 5;
System.out.println(bonus);
} // 'bonus' leaves scope here
int bonus = 20; // Compiles! Previous 'bonus' is no longer in scope
System.out.println(bonus);
}
}
Because the first bonus was declared inside the if block, it leaves scope at the closing } of the if block. Declaring a new int bonus = 20; afterward is therefore completely legal, whereas declaring int level = 99; inside the if block while parameter level is still in scope fails with variable level is already defined.
Java Source File & Class Structure
Every .java compilation unit follows a strict top-to-bottom ordering rule often remembered with the mnemonic PIC (Package, Imports, Classes/types):
- Package declaration (optional, at most one): Must appear before any
importor type declaration. - Import declarations (optional, zero or more): Must appear after
package(if present) and before any type declaration. - Top-level type declarations (
class,interface,enum,@interface): Zero or more.
Comments (//, /* ... */, and /** ... */) and blank lines are allowed anywhere in the file—before package, between import statements, or after the closing brace of a class.
| File Element | Max Per .java File | Required Order | Naming Rule |
|---|---|---|---|
package statement | 1 | Before imports and type declarations | Package name supplies the qualified class name. Match its directory layout when organizing source paths and class paths. |
import statements | Unlimited | After package, before any type | No |
public top-level type | At most 1 | After package and import | Yes (exact case-sensitive match) |
Non-public top-level types | Unlimited | After package and import | No |
Inside a class body, members (fields, constructors, methods, and initializer blocks) can appear in any order relative to one another. One subtle exam rule involves forward field references: a field initializer cannot read a field declared below it by simple name (int a = b; above int b = 5; fails to compile with illegal forward reference), although qualifying the access as this.b or reading through a method can compile. In this example the read sees b’s default value 0 before its initializer runs.
Multiple Classes in One .java File
A common misconception is that a .java file can contain only one class. In fact, a single file named Helpers.java can define multiple top-level classes as long as at most one is public (and if one is public, its name must be Helpers):
// File: InvoiceRunner.java
package billing;
import java.math.BigDecimal;
class TaxRule { // package-private top-level class
BigDecimal rate = new BigDecimal("0.08");
}
public class InvoiceRunner { // public class MUST match InvoiceRunner.java
public static void main(String[] args) {
TaxRule rule = new TaxRule();
System.out.println(rule.rate);
}
}
From the folder containing the source file, run javac -d . InvoiceRunner.java. This writes TaxRule.class and InvoiceRunner.class under billing/. If you add public in front of TaxRule, compilation fails because class TaxRule is public, should be declared in a file named TaxRule.java.
Valid Java SE 8 Identifiers
Identifiers name packages, classes, methods, variables, and labels. Java SE 8 enforces four rules:
- First character: Must satisfy
Character.isJavaIdentifierStart. Examples include letters, currency symbols such as$, and connector punctuation such as_. A digit cannot start the name. - Subsequent characters: Must satisfy
Character.isJavaIdentifierPart. Digits and certain additional Unicode characters are allowed here. - No spaces or operators: Characters such as
-,.,@,#, and spaces are illegal. - Not a reserved word: Identifiers cannot match any Java keyword (including the unused reserved keywords
gotoandconst) or the boolean/null literalstrue,false, andnull.
Note
In Java SE 8, a lone underscore _ is still a valid identifier (though javac emits a deprecation warning that _ may not be supported after Java SE 8). Starting in Java 9, _ became a reserved keyword. An ordinary declaration such as int _ = 42; compiles in Java 8. Java 8 already prohibits _ as a lambda parameter name.
| Identifier | Valid in Java SE 8? | Reason |
|---|---|---|
$price | Yes | Starts with allowed currency symbol $ |
_total2 | Yes | Starts with _ and contains letters and digit |
_ | Yes (with warning) | Legal single-character identifier in Java 8 |
2fast | No | Starts with a digit |
user-id | No | Hyphen - is the subtraction operator |
const | No | Reserved unused keyword in Java |
goto | No | Reserved unused keyword in Java |
Public | Yes | Case-sensitive; public is a keyword, Public is not |
Given the following class inside a single file named Tracker.java, what is the result?
public class Tracker {
int count = 5;
public void update(int count) {
if (count > 0) {
int step = count;
System.out.print(step + " ");
}
int step = this.count;
System.out.print(step);
}
public static void main(String[] args) {
new Tracker().update(3);
}
}
Compilation fails because count is declared both as an instance field and a method parameter
Compilation fails because step is declared twice inside update
It compiles and prints 3 5
It compiles and prints 3 3
Which source file arrangement compiles without error when saved in OrderApp.java?
/* Header comment */
package store;
import java.util.*;
class Helper {}
public class OrderApp {}
import java.util.*;
package store;
public class OrderApp {}
package store;
public class Helper {}
public class OrderApp {}
package store;
package store.sub;
public class OrderApp {}
Which of the following is NOT a valid variable identifier in Java SE 8?
$amount
_
String
goto
Sections you finish are checked off in the contents.