# AP® Computer Science A 3.7 Class Variables and Methods

Source: https://lockincs.com/ap-csa/unit-3/3-7-class-variables-and-methods/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 3.7.A, 3.7.A.1, 3.7.A.2, 3.7.B, 3.7.B.1, 3.7.B.2, 3.7.B.3

A class variable is declared with the static keyword and belongs to the class, so all objects share a single copy. Class methods can use class variables and call other class methods, but they cannot use instance variables or instance methods unless an object is passed in as a parameter. A variable declared final cannot be changed.

## What you will learn

- 3.7.A Develop code to define behaviors of a class through class methods.
- 3.7.B Develop code to declare the class variables that belong to the class.

## 1\. Class variables: one shared copy

**Class variables** belong to the class, and all objects of the class share a single copy. They are marked with the keyword `static` before the variable type 3.7.B.1. Instance variables are the opposite: each object has its own copy.

This class is used on the whole page:

```
public class Ticket
{
    public static final int MAX_TICKETS = 100;   // class variable, final
    private static int nextNumber = 1;           // class variable

    private String event;                        // instance variable
    private int number;                          // instance variable

    public Ticket(String eventName)
    {
        event = eventName;
        number = nextNumber;
        nextNumber++;
    }

    public int getNumber()
    {
        return number;
    }

    public static int ticketsIssued()
    {
        return nextNumber - 1;
    }

    public static int ticketsLeft()
    {
        return MAX_TICKETS - ticketsIssued();
    }

    public static boolean isEarlier(Ticket a, Ticket b)
    {
        return a.number < b.number;
    }

    public String toString()
    {
        return event + " #" + number;
    }
}
```

```
Ticket t1 = new Ticket("Concert");
Ticket t2 = new Ticket("Concert");
Ticket t3 = new Ticket("Match");
System.out.println(t1 + ", " + t2 + ", " + t3);
System.out.println(Ticket.ticketsIssued());
```

Output:

```
Concert #1, Concert #2, Match #3
3
```

Memory after the code runs:

```
class Ticket:   MAX_TICKETS 100   nextNumber 4     (one copy, shared)

t1 [ ref ] ---> Ticket object: event "Concert"  number 1
t2 [ ref ] ---> Ticket object: event "Concert"  number 2
t3 [ ref ] ---> Ticket object: event "Match"    number 3
```

Printing a `Ticket` uses its `toString` method (background only: writing `toString` is outside the AP® exam). Every constructor call read and changed the **same** `nextNumber`. That is how each ticket gets a different number.

## 2\. Using a public class variable from outside

A class variable that is `public` is accessed outside the class with the **class name and the dot operator**, because it is associated with the class, not with objects of the class 3.7.B.2. This is a new program, so no tickets exist before it runs:

```
System.out.println("Limit: " + Ticket.MAX_TICKETS);
Ticket t = new Ticket("Play");
System.out.println("Left: " + Ticket.ticketsLeft());
```

Output:

```
Limit: 100
Left: 99
```

You do not need any `Ticket` object to read `Ticket.MAX_TICKETS`. A private class variable such as `nextNumber` cannot be used from outside at all: other classes use the public class method `ticketsIssued` instead.

## 3\. final: a value that cannot change

When a variable is declared `final`, its value cannot be modified 3.7.B.3. Constants are usually `public static final`, with a name in capital letters.

```
Ticket.MAX_TICKETS = 500;
```

Compiler says:

```
error: cannot assign a value to static final variable MAX_TICKETS
```

`final` works for local variables too:

```
final double TAX_RATE = 0.08;
double price = 50.0;
System.out.println(price + price * TAX_RATE);
```

Output:

```
54.0
```

## 4\. What class methods can do

A **class method** (a `static` method) can access or change the values of class variables, and it can call other class methods 3.7.A.2.

In `Ticket`, the class method `ticketsIssued` reads the class variable `nextNumber`, and the class method `ticketsLeft` calls the class method `ticketsIssued`. A class method can also change a class variable:

```
public class Scoreboard
{
    private static int games = 0;
    private static int totalGoals = 0;

    public static void recordGame(int goals)
    {
        games++;
        totalGoals += goals;
    }

    public static double averageGoals()
    {
        return (double) totalGoals / games;
    }

    public static String report()
    {
        return games + " games, " + averageGoals() + " goals per game";
    }
}
```

```
Scoreboard.recordGame(3);
Scoreboard.recordGame(0);
Scoreboard.recordGame(2);
System.out.println(Scoreboard.report());
```

Output:

```
3 games, 1.6666666666666667 goals per game
```

## 5\. What class methods cannot do (without an object)

Class methods **cannot** access or change instance variables, or call instance methods, unless an instance of the class is passed to them through a parameter 3.7.A.1. A class method is called on the class, so there is no “current object” whose instance variables it could use.

```
public class Seat
{
    private int row;

    public Seat(int r)
    {
        row = r;
    }

    public static boolean isFrontRow()
    {
        return row == 1;
    }
}
```

Compiler says:

```
error: non-static variable row cannot be referenced from a static context
```

The fix is to pass an object in. `Ticket.isEarlier` does exactly that: it receives two `Ticket` objects and uses their instance variables.

```
Ticket a = new Ticket("Concert");
Ticket b = new Ticket("Concert");
System.out.println(Ticket.isEarlier(a, b));
System.out.println(Ticket.isEarlier(b, a));
```

Output:

```
true
false
```

Calling an instance method from a class method without an object fails the same way:

```
public class Clock
{
    private int minutes;

    public int getMinutes()
    {
        return minutes;
    }

    public static int getHours()
    {
        return getMinutes() / 60;
    }
}
```

Compiler says:

```
error: non-static method getMinutes() cannot be referenced from a static context
```

|  | Can use instance variables and instance methods? | Can use class variables and class methods? |
| --- | --- | --- |
| Instance method | Yes | Yes |
| Class method | Only through an object parameter 3.7.A.1 | Yes 3.7.A.2 |

## Common mix-ups

- Not true: Each object gets its own copy of a static variable. A static (class) variable belongs to the class. There is exactly one copy, and every object of the class shares it, so a change made through one object is seen by all.
- Not true: A static method can use any instance variable of its class. A class method is not called on an object, so there is no instance variable to use. It can only reach instance data through an object passed to it as a parameter.
- Not true: final means the variable is private. final means the value cannot be modified after it is set. Access is a separate choice: a final variable can be public or private.

## In 30 seconds

- Class variables belong to the class; all objects share a single copy; declared with static before the type.
- A public class variable is used outside the class as ClassName.variableName.
- A final variable cannot be modified after it gets its value.
- Class methods can access and change class variables and call other class methods.
- Class methods cannot use instance variables or call instance methods unless an object is passed in as a parameter.

## Checkpoint: 5 practice questions

### Question 1

Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment?

```java
public class Visitor
{
    private static int count = 0;
    private int id;

    public Visitor()
    {
        count++;
        id = count;
    }

    public int getId()
    {
        return id;
    }

    public static int getCount()
    {
        return count;
    }
}

Visitor v1 = new Visitor();
Visitor v2 = new Visitor();
Visitor v3 = v2;
Visitor v4 = new Visitor();
System.out.println(v1.getId() + " " + v3.getId() + " " + Visitor.getCount());
```

- A. 1 2 4
- B. 1 3 3
- C. 1 2 3
- D. 3 3 3

**Answer: C.** `count` is a class variable, so all objects share one copy and it counts constructor calls. Only three objects are created: `v3 = v2` copies a reference and does not call the constructor, so the count is 3 and `v3` has the same id as `v2`, which is 2. The option 1 2 4 counts `v3` as a new object, and 3 3 3 treats `id` as if it were shared too.

### Question 2

Consider the following incomplete class. The class method `area` is intended to return the area of the rectangle passed to it. Which of the following can replace `/* missing code */` so that `area` works as intended?

```java
public class Rectangle
{
    private int width;
    private int height;

    public Rectangle(int w, int h)
    {
        width = w;
        height = h;
    }

    public static int area(Rectangle r)
    {
        /* missing code */
    }
}
```

- A. `return r.width * r.height;`
- B. `return width * height;`
- C. `return this.width * this.height;`
- D. `return r.getArea();`

**Answer: A.** A class method cannot use instance variables without an object, but here an object is passed in as `r`, and because `area` is inside `Rectangle` it may read `r`'s private variables. Using `width` alone, or `this`, does not compile in a static method because there is no current object. `Rectangle` has no `getArea` method.

### Question 3

A class `Game` contains the declaration `public static final int MAX_LEVEL = 10;`. Which of the following statements, appearing in a method of another class, compiles without error?

```java
public class Game
{
    public static final int MAX_LEVEL = 10;
}
```

- A. `Game.MAX_LEVEL = 12;`
- B. `int m = Game.maxLevel;`
- C. `int m = MAX_LEVEL;`
- D. `int m = Game.MAX_LEVEL;`

**Answer: D.** A public class variable is accessed outside its class with the class name and the dot operator, exactly as declared: `Game.MAX_LEVEL`. It is `final`, so assigning 12 to it does not compile. Java is case-sensitive, so `maxLevel` is a different, undeclared name, and without `Game.` the other class cannot find `MAX_LEVEL`.

### Question 4

Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment?

```java
public class Tally
{
    private static int total = 0;

    public static void add(int n)
    {
        total += n;
    }

    public static void addTwice(int n)
    {
        add(n);
        add(n);
    }

    public static int getTotal()
    {
        return total;
    }
}

Tally.add(5);
Tally.addTwice(3);
Tally.add(-2);
System.out.println(Tally.getTotal());
```

- A. 6
- B. 9
- C. 11
- D. 0

**Answer: B.** Class methods can change class variables and call other class methods. `total` becomes 5, then `addTwice(3)` calls `add` twice to reach 11, then `add(-2)` gives 9. The option 6 counts `addTwice` as one addition, 11 forgets the last call, and 0 wrongly assumes that class methods cannot change the class variable.

### Question 5

The following method is written inside a `Player` class that has the instance variable `private int score;`. Which of the following best describes the result?

```java
public static void reset()
{
    score = 0;
}
```

- A. It compiles and sets the score of every `Player` object to 0
- B. It compiles and sets the score of the most recently created `Player` object to 0
- C. It compiles, but calling it causes a `NullPointerException`
- D. It does not compile, because there is no object whose `score` it could change

**Answer: D.** A class method is not called on an object, so it has no instance variable named `score` to change, and the compiler reports that a non-static variable cannot be referenced from a static context. A static method does not loop over all objects or pick one, and the problem is found at compile time, not at run time. Passing a `Player` parameter, such as `p.score = 0;`, would fix it.

## Questions students ask

**What is a static variable in Java?**

A static variable, or class variable, belongs to the class instead of to any one object. All objects of the class share a single copy, so it is often used for counters and shared settings.

**Why can't a static method use instance variables?**

A static method is called on the class, not on an object, so there is no current object whose instance variables it could use. Pass an object as a parameter and use it, such as a.getNumber().

**How do you access a public static variable from another class?**

Use the class name and the dot operator, such as Ticket.MAX_TICKETS, because the variable is associated with the class, not with objects of the class.

**What does final mean for a variable?**

A final variable cannot be modified once it has a value. Constants such as public static final int MAX_TICKETS = 100; are written with final.

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
