A query during class initialization

A venue application loads this Java class for the first time. Predict its query results using the initialization rules supplied below.


Java
public class GateSettings {
    private static int openingLimit = readLimit();
    private static int limit = 9;

    public static int readLimit() {
        return limit;
    }

    public static int readOpening() {
        return openingLimit;
    }

    public static void addToLimit(int amount) {
        limit += amount;
    }
}


For this problem, use these Java rules:

  • Before the explicit static field assignments run, all static int fields initially contain 0.
  • Static field initializers then run once, in their written order, when the class is initialized.
  • A static initializer may call a static method. That method reads the field values that exist at the time of the call.
  • Creating further objects of an already initialized class does not repeat its static initialization.

The application executes the following stages in order. At each stage, the queries only read values.

  1. Call GateSettings.readOpening(), then GateSettings.readLimit(), before creating any GateSettings objects.
  2. Execute GateSettings.addToLimit(4), create one GateSettings object, then call both queries again.
  3. Create a second GateSettings object, execute GateSettings.addToLimit(-3), then call both queries again.

Complete the table with the exact integer returned by each query. The limits represent numbers of visitors.

StagereadOpening resultreadLimit result
1
2
3

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Static Keyword and Class Methods Questions: