AP Computer Science A · Study guide

Class Variables and Constants

AP® Computer Science A · Class Creation

Class Variables and Constants

Variables that belong to a class rather than to each object: declaring them with static, sharing one copy among all objects, reaching public ones with the class name, and fixing values permanently with final.

Big Picture

Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. They are designated with the static keyword before the variable type. Class variables designated public are accessed outside the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. When a variable is declared final, its value cannot be modified, which is how Java expresses named constants.

1Declaring Class Variables

A class variable is declared in the class body, outside every method and constructor, with the keyword static before its type: private static int totalLaps = 0;. It can be given a starting value right in the declaration, and that value is set once, when the class is first used, not each time an object is created.

Class variables hold information about the class as a whole: how many objects have been created, the next id to hand out, a setting that applies to every object, or a fixed constant. Like instance variables, they are usually private, with class methods or instance methods providing controlled access.

Because a class variable is not tied to any object, it exists even before the first object is created and keeps its value as objects come and go. A counter of created objects starts at 0 the moment the class is first used, increases with each constructor call, and keeps its total for the rest of the program.

Instance variableClass variable
Declarationprivate int laps;private static int totalLaps;
CopiesOne per objectOne for the whole class
Accessed from outside (if public)object.nameClassName.name
Changed by one objectOnly that object sees itEvery object sees it

2One Copy Shared by All Objects

Class variables belong to the class, with all objects of a class sharing a single copy. Every object's methods read and write that same copy, so a change made through one object is immediately visible through all the others, and through class methods as well.

This is exactly right for shared information such as a running total, and exactly wrong for information that should differ between objects. If each player needs a separate score, score must be an instance variable; declaring it static makes every player share one score, and creating or updating any player changes it for all of them.

Figure 1. Class variables belong to the class, with all objects of the class sharing a single copy. They are designated with the keyword static.
Worked Example 1 A shared class variable

Counting Laps for Everyone

Each runner counts its own laps; a class variable counts everyone's. Predict the output.

The Runner class and a short program
public class Runner
{
    private static int totalLaps = 0;
    private int laps;
    private String name;

    public Runner(String n)
    {
        name = n;
        laps = 0;
    }

    public void completeLap()
    {
        laps++;
        totalLaps++;
    }

    public String report()
    {
        return name + " " + laps + " of " + totalLaps;
    }

    public static int getTotalLaps()
    {
        return totalLaps;
    }
}
Output
Ines 2 of 3
Tavi 1 of 3
3
  1. 1laps is per object: Ines has 2, Tavi has 1.
  2. 2totalLaps is shared: every call to completeLap increases the one copy, so both reports show 3.
  3. 3Runner.getTotalLaps() reads the same shared value through a class method.
Result: The output is Ines 2 of 3, Tavi 1 of 3, and 3. All objects of a class share a single copy of each class variable, so a change made through one object is seen by all.
Worked Example 2 A shared setting

Changing One Setting for Every Object

All thermometers share one display setting. Predict the output.

A Thermometer class with a shared setting
public class Thermometer
{
    private static boolean showFahrenheit = false;
    private double celsius;

    public Thermometer(double c)
    {
        celsius = c;
    }

    public static void useFahrenheit(boolean on)
    {
        showFahrenheit = on;
    }

    public String reading()
    {
        if (showFahrenheit)
        {
            return (celsius * 9 / 5 + 32) + " F";
        }
        return celsius + " C";
    }
}
Output
20.0 C, 5.0 C
68.0 F, 41.0 F
  1. 1Per-object data. Each thermometer keeps its own celsius reading.
  2. 2Shared setting. showFahrenheit is one class variable, changed by the class method useFahrenheit.
  3. 3One change, every object. After the call, both thermometers report in Fahrenheit: 20 °C is 68.0 °F and 5 °C is 41.0 °F.
Result: The output changes from 20.0 C, 5.0 C to 68.0 F, 41.0 F. Because all objects share a single copy of a class variable, changing it changes the behavior of every object at once.
Worked Example 3 A common bug

Per-Player Data Declared static

The programmer accidentally made score a class variable. Predict the output.

A Player class with a mistaken static
public class Player
{
    private static int score;
    private String name;

    public Player(String n)
    {
        name = n;
        score = 0;
    }

    public void addPoints(int p)
    {
        score = score + p;
    }

    public String show()
    {
        return name + ": " + score;
    }
}
Output
Oro: 5
Lumi: 5
  1. 1One shared score. Because score is static, both players use the same variable.
  2. 2Creating Lumi runs the constructor, which resets the shared score to 0, wiping out Oro's 30 points; Lumi's 5 points then apply to the shared copy.
  3. 3Fix. Remove static so each player has its own score.
Result: Both lines show 5. Data that should differ from object to object must be an instance variable; making it static silently merges every object's value into one.
Common Mistake 1 · Making Per-Object Data static

If a value should be different for each object, such as a name, a score, or a position, it must not be static. A static field has only one copy, so every object would overwrite the others' values.

3Accessing Class Variables From Outside

Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. Pool.LANE_COUNT needs no Pool object. Inside the class itself, the variable's name alone is enough.

The Java library uses the same pattern. Integer.MAX_VALUE and Integer.MIN_VALUE are public class variables of the Integer class, holding the largest and smallest int values. Public class variables are almost always also final, so that outside code can read them but never change them.

A class variable that is private cannot be reached by name from other classes at all. When outside code needs its value, the class provides a public class method, such as Runner.getTotalLaps(), which returns a copy. This keeps the shared value under the class's control while still making it available.

Figure 2. Class variables designated public are accessed outside the class by using the class name and the dot operator.
Library class constantValue
Integer.MAX_VALUE2147483647, the largest int
Integer.MIN_VALUE−2147483648, the smallest int
Worked Example 4 Public class constants

Using a Constant From Another Class

Predict the output.

A Pool class with constants
public class Pool
{
    public static final int LANE_COUNT = 8;
    public static final double LENGTH_M = 25.0;

    public static double distance(int lengths)
    {
        return lengths * LENGTH_M;
    }
}
Output
8
400.0
16
true
  1. 1Class name, dot, variable. Pool.LANE_COUNT reads the public class variable without any Pool object.
  2. 2Inside the class, distance uses LENGTH_M by name: 16 × 25.0 = 400.0.
  3. 3Library constants such as Integer.MAX_VALUE are public class variables reached the same way.
Result: The output is 8, 400.0, 16, true. Class variables designated public are accessed outside the class by using the class name and the dot operator.

4final: Values That Cannot Change

When a variable is declared final, its value cannot be modified. A final variable is assigned exactly once, and any later assignment is a compile-time error: "cannot assign a value to final variable." This turns an intention ("this number should never change") into a rule the compiler enforces.

final applies to instance variables as well as class variables. A final instance variable, such as a race bib number, is assigned in the constructor and then stays fixed for that object's lifetime, while each object still has its own value.

The keyword can also be applied to local variables inside a method, as in final int limit = 10;. The rule is the same everywhere: once a final variable has its value, no statement may change it. Using final wherever a value is meant to stay fixed documents that intent and lets the compiler catch accidental changes.

Figure 3. When a variable is declared final, its value cannot be modified. The compiler rejects any later assignment.
Worked Example 5 final

Trying to Change a Constant

Explain the compile error.

Code that does not compile
public class Pool
{
    public static final int LANE_COUNT = 8;
}
  1. 1final means fixed. LANE_COUNT was given its value once, and no later assignment is allowed.
  2. 2The compiler enforces it, so a constant can never be changed by mistake anywhere in the program.
Result: The code does not compile. When a variable is declared final, its value cannot be modified.
Worked Example 6 final instance variables

A Value Each Object Keeps Forever

Each runner gets a bib number that never changes. Predict the output.

An Entrant class with a final instance variable
public class Entrant
{
    private static int nextBib = 100;
    private final int bib;
    private int laps;

    public Entrant()
    {
        bib = nextBib;
        nextBib++;
        laps = 0;
    }

    public void completeLap()
    {
        laps++;
    }

    public String tag()
    {
        return "#" + bib + " laps " + laps;
    }
}
Output
#100 laps 0
#101 laps 1
  1. 1nextBib is a class variable that hands out numbers: 100, then 101.
  2. 2bib is a final instance variable: each entrant has its own, assigned once in the constructor and never changed.
  3. 3laps changes freely because it is not final.
Result: The output is #100 laps 0 and #101 laps 1. final works for instance variables too: each object's value is set once and then fixed.
Common Mistake 2 · Assigning a final Instance Variable Outside the Constructor

A final instance variable must receive its value in its declaration or in every constructor; a mutator that assigns it does not compile. If a value must change later, it should not be final.

5static and final Together: Constants

A variable that is both static and final is a class constant: one shared copy whose value never changes, such as public static final int LANE_COUNT = 8;. By convention, constant names are written in capital letters with underscores between words, which makes them easy to recognize in code.

Named constants make programs clearer and safer than repeating literal numbers. lengths * LENGTH_M explains itself where lengths * 25.0 does not, and if the pool length ever changes, only one line must be edited. Because a constant is final, making it public does not weaken encapsulation: other classes can read it but cannot alter it.

Figure 4. static decides how many copies exist; final decides whether the value can change.
DeclarationCopiesCan change?Typical use
private int laps;per objectyesOrdinary attribute
private static int totalLaps;one sharedyesCounter or shared setting
private final int bib;per objectno (after constructor)Identifier fixed at creation
public static final int LANE_COUNT = 8;one sharednoNamed constant
Worked Example 7 Constants in logic

A Named Pass Mark

Predict the output.

A Grader class with named constants
public class Grader
{
    public static final int PASS_MARK = 60;
    public static final int TOP_MARK = 90;

    public static String verdict(int score)
    {
        if (score >= TOP_MARK)
        {
            return "distinction";
        }
        if (score >= PASS_MARK)
        {
            return "pass";
        }
        return "retake";
    }
}
Output
distinction
pass
retake
Pass mark: 60
  1. 1Readable conditions. score >= PASS_MARK says what the 60 means.
  2. 2Boundaries. 95 reaches the top mark; 60 is exactly the pass mark; 59 falls just short.
  3. 3Outside access. Other classes can read Grader.PASS_MARK, but because it is final, none can change it.
Result: The output is distinction, pass, retake, and Pass mark: 60. Named constants make conditions self-explanatory and keep a value defined in exactly one place.
Common Mistake 3 · Repeating Magic Numbers

Writing 25.0 in a dozen places makes code hard to read and easy to break: change one and miss another, and the program becomes inconsistent. Declare a named constant once and use its name everywhere.

6Choosing static and final Carefully

Two questions decide each attribute's declaration. First, should every object have its own value, or should one value be shared by the whole class? That decides static. Second, should the value ever change after it is set? That decides final. Answering both questions for every attribute in a class design prevents the most common mistakes.

Shared, changeable class variables should be used sparingly, because any part of the class can change them and every object is affected. Counters and id generators are good uses. Constants, by contrast, are safe to share widely and are encouraged wherever a fixed value has a meaning worth naming.

Common Mistake 4 · Accessing a Class Variable Through an Object

Java allows a.totalLaps inside the class, but it suggests that the value belongs to a, which it does not. Refer to class variables by name inside the class, and with the class name outside it: Runner.getTotalLaps() or Pool.LANE_COUNT.

Four Habits for Class Variables

1. static = One Copy

Shared by every object of the class.

2. Per-Object Data Is Not static

Names, scores, positions belong to each object.

3. ClassName.variable

Reach public class variables through the class.

4. final for Fixed Values

static final for named constants in CAPITALS.

Core Synthesis

Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type. Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. When a variable is declared final, its value cannot be modified; a variable that is both static and final is a shared constant.