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

Last updated: November 2026

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 KindWhere DeclaredScopeDefault Value?
Local variableInside a method, constructor, initializer block, or for-loop headerFor 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 parameterParameter list of a method or constructorEntire body of that method or constructorNo (receives caller's argument)
Instance variable (field)Inside a class body, outside methods/blocks, without staticEntire class; accessible via an instance from static contextsYes (0, 0.0, false, \u0000, null)
Class (static) variableInside a class body, outside methods/blocks, with staticEntire 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:

  1. Conditional initialization: If the else branch were omitted, balance -= fee; would fail with variable fee might not have been initialized, even if you mentally trace waive as true at runtime. The compiler checks definite assignment statically.
  2. for-loop header scope: A variable declared in a for header (int step = 0) is scoped to the for statement only. Referencing step immediately 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):

  1. Package declaration (optional, at most one): Must appear before any import or type declaration.
  2. Import declarations (optional, zero or more): Must appear after package (if present) and before any type declaration.
  3. 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 ElementMax Per .java FileRequired OrderNaming Rule
package statement1Before imports and type declarationsPackage name supplies the qualified class name. Match its directory layout when organizing source paths and class paths.
import statementsUnlimitedAfter package, before any typeNo
public top-level typeAt most 1After package and importYes (exact case-sensitive match)
Non-public top-level typesUnlimitedAfter package and importNo

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 goto and const) or the boolean/null literals true, false, and null.

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.

IdentifierValid in Java SE 8?Reason
$priceYesStarts with allowed currency symbol $
_total2YesStarts with _ and contains letters and digit
_Yes (with warning)Legal single-character identifier in Java 8
2fastNoStarts with a digit
user-idNoHyphen - is the subtraction operator
constNoReserved unused keyword in Java
gotoNoReserved unused keyword in Java
PublicYesCase-sensitive; public is a keyword, Public is not
Loading diagram...
Top-to-Bottom Structure of a .java Source File
Test Your Knowledge

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);
    }
}
A

Compilation fails because count is declared both as an instance field and a method parameter

B

Compilation fails because step is declared twice inside update

C

It compiles and prints 3 5

D

It compiles and prints 3 3

Test Your Knowledge

Which source file arrangement compiles without error when saved in OrderApp.java?

A
/* Header comment */
package store;
import java.util.*;
class Helper {}
public class OrderApp {}
B
import java.util.*;
package store;
public class OrderApp {}
C
package store;
public class Helper {}
public class OrderApp {}
D
package store;
package store.sub;
public class OrderApp {}
Test Your Knowledge

Which of the following is NOT a valid variable identifier in Java SE 8?

A

$amount

B

_

C

String

D

goto

Sections you finish are checked off in the contents.