Class Variables and Methods

Help Questions

AP Computer Science A › Class Variables and Methods

Questions 1 - 10
1

How does the static method interact with the class variable in this code?


// BankAccount demonstrates class variables (static) and class methods (static).

public class BankAccount {

    // Class variable shared by all accounts in the bank.

    private static double bankTotalBalance = 0.0;

    // Instance variable unique to each BankAccount object.

    private double accountBalance;

    // Constructor initializes an account with an opening deposit.

    public BankAccount(double openingDeposit) {

        accountBalance = openingDeposit;

        // Update the class-level total whenever an account is created.

        bankTotalBalance += openingDeposit;

    }

    // Static (class) method returns the total balance across all accounts.

    public static double getBankTotalBalance() {

        return bankTotalBalance;

    }

    // Instance method deposits money into this account and updates the class total.

    public void deposit(double amount) {

        accountBalance += amount;

        bankTotalBalance += amount;

    }

    // Instance method withdraws money from this account and updates the class total.

    public void withdraw(double amount) {

        accountBalance -= amount;

        bankTotalBalance -= amount;

    }

    // Main method demonstrates creating accounts and adjusting balances.

    public static void main(String[] args) {

        BankAccount a = new BankAccount(100.0);

        BankAccount b = new BankAccount(50.0);

        a.deposit(25.0);

        b.withdraw(10.0);

        System.out.println(BankAccount.getBankTotalBalance());

    }

}

It cannot access bankTotalBalance because it is a static variable.

It creates a separate bankTotalBalance copy per BankAccount instance.

It updates only the calling object’s accountBalance value.

It returns the shared bankTotalBalance for all BankAccount objects.

Explanation

This question tests understanding of class variables and methods in Java, focusing on how static methods interact with static variables. Class variables (static variables) are shared among all instances of a class, and static methods can access these variables directly without needing an object reference. Choice B is correct because the getBankTotalBalance() method is static and returns the value of the static variable bankTotalBalance, which is shared across all BankAccount objects. Choice A is incorrect because it confuses static methods with instance methods - static methods don't operate on a specific object's data. To help students: Use diagrams showing how static variables exist at the class level rather than instance level. Practice tracing through code where multiple objects modify the same static variable to reinforce the shared nature of class variables.

2

What will be the output when the main method is executed?


// Student demonstrates class variables (static) and class methods (static).

public class Student {

    // Class variable tracking total enrolled students across all instances.

    private static int totalEnrolled = 0;

    // Instance variable indicating whether this student is currently enrolled.

    private boolean enrolled;

    // Constructor enrolls the student upon creation.

    public Student() {

        enrolled = true;

        totalEnrolled++;

    }

    // Instance method withdraws this student and updates the class total.

    public void withdraw() {

        if (enrolled) {

            enrolled = false;

            totalEnrolled--;

        }

    }

    // Static method returns total enrolled students.

    public static int getTotalEnrolled() {

        return totalEnrolled;

    }

    // Main method simulates enrollment and withdrawal.

    public static void main(String[] args) {

        Student s1 = new Student();

        Student s2 = new Student();

        s1.withdraw();

        Student s3 = new Student();

        System.out.println(Student.getTotalEnrolled());

    }

}

The program will not compile due to static misuse.

3

2

1

Explanation

This question tests understanding of class variables and methods in Java, specifically tracking how static variables change as objects are created and modified. The static variable totalEnrolled is shared among all Student instances and tracks the total number of enrolled students. Choice B is correct because: s1 is created (totalEnrolled = 1), s2 is created (totalEnrolled = 2), s1 withdraws (totalEnrolled = 1), s3 is created (totalEnrolled = 2), so the output is 2. Choice C is incorrect because it fails to account for the withdrawal of s1, which decrements the total. To help students: Create step-by-step traces showing how static variables change with each operation. Use visual representations showing the single static variable being modified by multiple objects to reinforce the shared nature of class variables.

3

Which line of code demonstrates the use of a class method?


// Library demonstrates a class variable and static methods.

public class Library {

    // Class variable shared by the entire library.

    private static int totalBooks = 0;

    // Constructor adds books to the library's shared total.

    public Library(int initialBooks) {

        totalBooks += initialBooks;

    }

    // Instance method checks out a book and updates the shared total.

    public void checkOutBook() {

        if (totalBooks > 0) {

            totalBooks--;

        }

    }

    // Static (class) method returns the current total books.

    public static int getTotalBooks() {

        return totalBooks;

    }

    // Main method demonstrates usage.

    public static void main(String[] args) {

        Library branch = new Library(3);

        branch.checkOutBook();

        System.out.println(Library.getTotalBooks());

    }

}

totalBooks += initialBooks;

System.out.println(Library.getTotalBooks());

Library branch = new Library(3);

branch.checkOutBook();

Explanation

This question tests understanding of class variables and methods in Java, focusing on identifying static method calls versus instance method calls. Class methods (static methods) are called using the class name rather than an object reference, though they can also be called through an object. Choice C is correct because Library.getTotalBooks() demonstrates calling a static method using the class name Library, which is the conventional way to call class methods. Choice B is incorrect because checkOutBook() is an instance method called on the branch object, not a class method. To help students: Emphasize the syntax difference between ClassName.staticMethod() and objectName.instanceMethod(). Practice identifying static versus instance methods in code and explaining why each is appropriate for its use case.

4

What would happen if the class variable were not static?


// ECommerceInventory demonstrates a class variable tracking total sales.

public class ECommerceInventory {

    // Class variable shared across all transactions.

    private static int totalSales = 0;

    // Constructor does not change totalSales; sales occur via methods.

    public ECommerceInventory() {

        // No instance-specific setup needed for this example.

    }

    // Instance method processes a sale and updates the shared total.

    public void processSale(int itemsSold) {

        totalSales += itemsSold;

    }

    // Instance method processes a return and updates the shared total.

    public void processReturn(int itemsReturned) {

        totalSales -= itemsReturned;

    }

    // Static method returns the shared total sales.

    public static int getTotalSales() {

        return totalSales;

    }

    // Main method demonstrates multiple objects affecting the same total.

    public static void main(String[] args) {

        ECommerceInventory t1 = new ECommerceInventory();

        ECommerceInventory t2 = new ECommerceInventory();

        t1.processSale(5);

        t2.processSale(2);

        System.out.println(ECommerceInventory.getTotalSales());

    }

}

Each object would track its own totalSales independently.

totalSales would become inaccessible outside the main method scope.

The program would not compile because static methods require static variables.

All objects would still share one totalSales value automatically.

Explanation

This question tests understanding of class variables and methods in Java, specifically the impact of removing the static keyword from a class variable. When a variable is static, it belongs to the class and is shared by all instances; without static, each instance gets its own copy. Choice A is correct because removing static from totalSales would make it an instance variable, meaning each ECommerceInventory object would have its own separate totalSales value that wouldn't be shared. Choice B is incorrect because static methods can access instance variables through object references, though they cannot access them directly without an object. To help students: Use memory diagrams showing the difference between one shared static variable versus multiple instance variables. Create examples where removing static breaks the intended functionality to highlight the importance of proper variable scope.

5

How does the class variable affect the behavior of this code?


// BankAccount uses a shared class variable to track total bank funds.

public class BankAccount {

    // Class variable shared across all BankAccount objects.

    private static double bankTotalBalance = 0.0;

    // Instance variable for a single account.

    private double accountBalance;

    // Constructor adds opening deposit to both instance and class totals.

    public BankAccount(double openingDeposit) {

        accountBalance = openingDeposit;

        bankTotalBalance += openingDeposit;

    }

    // Instance method updates both this account and the shared total.

    public void deposit(double amount) {

        accountBalance += amount;

        bankTotalBalance += amount;

    }

    // Static method reads the shared total.

    public static double getBankTotalBalance() {

        return bankTotalBalance;

    }

    // Main method demonstrates shared state.

    public static void main(String[] args) {

        BankAccount x = new BankAccount(10.0);

        BankAccount y = new BankAccount(20.0);

        x.deposit(5.0);

        System.out.println(BankAccount.getBankTotalBalance());

    }

}

It prevents bankTotalBalance from being modified by instance methods.

It allows all accounts to contribute to one shared bankTotalBalance.

It causes each account to store a separate bankTotalBalance value.

It limits bankTotalBalance access to only the constructor method.

Explanation

This question tests understanding of class variables and methods in Java, focusing on how static variables enable shared state across multiple objects. The static keyword on bankTotalBalance makes it a class variable that all BankAccount instances share and can modify. Choice C is correct because the static bankTotalBalance variable is shared among all BankAccount objects, allowing each account's deposits and withdrawals to contribute to one cumulative total for the entire bank. Choice A is incorrect because it describes instance variable behavior, not static variable behavior - static variables are shared, not separate. To help students: Use real-world analogies like a shared bank vault versus individual safety deposit boxes. Trace through code execution showing how multiple objects affect the same static variable to reinforce the concept of shared state.

6

What will be the output when the main method is executed?


// Library tracks a shared total of books using a class variable.

public class Library {

    // Class variable shared by all Library objects.

    private static int totalBooks = 0;

    // Constructor adds initial books to the shared total.

    public Library(int initialBooks) {

        totalBooks += initialBooks;

    }

    // Instance method checks in a book and updates the shared total.

    public void checkInBook() {

        totalBooks++;

    }

    // Instance method checks out a book and updates the shared total.

    public void checkOutBook() {

        if (totalBooks > 0) {

            totalBooks--;

        }

    }

    // Static method returns the shared total.

    public static int getTotalBooks() {

        return totalBooks;

    }

    // Main method demonstrates multiple branches affecting one total.

    public static void main(String[] args) {

        Library a = new Library(2);

        Library b = new Library(1);

        a.checkOutBook();

        b.checkInBook();

        System.out.println(Library.getTotalBooks());

    }

}

0

2

3

4

Explanation

This question tests understanding of class variables and methods in Java, specifically tracking changes to a shared static variable through multiple operations. The static totalBooks variable is modified by constructors and instance methods across different Library objects. Choice B is correct because: Library a adds 2 books (totalBooks = 2), Library b adds 1 book (totalBooks = 3), a checks out 1 book (totalBooks = 2), b checks in 1 book (totalBooks = 3), so the output is 3. Choice C is incorrect because it likely miscounts the operations or misunderstands that checkInBook() increments rather than decrements. To help students: Create detailed execution traces showing each step's effect on the static variable. Use debugging techniques or print statements after each operation to visualize how the shared variable changes throughout program execution.

7

How does the static method interact with the class variable in this code?


// Student uses a class variable to count how many students are enrolled.

public class Student {

    // Class variable shared across all Student objects.

    private static int totalEnrolled = 0;

    // Constructor increments the shared count.

    public Student() {

        totalEnrolled++;

    }

    // Static method resets the shared count for a new term.

    public static void resetEnrollment() {

        totalEnrolled = 0;

    }

    // Static method returns the shared count.

    public static int getTotalEnrolled() {

        return totalEnrolled;

    }

    // Main method demonstrates static methods affecting class-level data.

    public static void main(String[] args) {

        Student a = new Student();

        Student b = new Student();

        Student.resetEnrollment();

        System.out.println(Student.getTotalEnrolled());

    }

}

It resets totalEnrolled for the entire class to 0.

It creates a new local variable totalEnrolled inside the method.

It cannot modify totalEnrolled because both are static.

It resets totalEnrolled only for object a, not b.

Explanation

This question tests understanding of class variables and methods in Java, focusing on how static methods can modify static variables that affect all instances. Static methods belong to the class rather than any specific instance and can directly access and modify static variables. Choice A is correct because resetEnrollment() is a static method that sets the static variable totalEnrolled to 0, which affects the entire class - this shared variable is the same one accessed by all Student objects. Choice B is incorrect because it misunderstands static variables as being instance-specific; static variables are shared across all instances, not unique to each object. To help students: Emphasize that static methods operate at the class level, not the instance level. Use examples showing how static method calls affect all existing and future instances by modifying shared class variables.

8

What would happen if the class variable were not static?


// BankAccount tracks bank-wide total funds using a static class variable.

public class BankAccount {

    // Class variable shared by all accounts.

    private static double bankTotalBalance = 0.0;

    // Instance variable per account.

    private double accountBalance;

    // Constructor updates both instance and shared totals.

    public BankAccount(double openingDeposit) {

        accountBalance = openingDeposit;

        bankTotalBalance += openingDeposit;

    }

    // Static method reads the shared total.

    public static double getBankTotalBalance() {

        return bankTotalBalance;

    }

    // Main method demonstrates shared total.

    public static void main(String[] args) {

        BankAccount a = new BankAccount(40.0);

        BankAccount b = new BankAccount(60.0);

        System.out.println(BankAccount.getBankTotalBalance());

    }

}

Each account would still share one bankTotalBalance automatically.

bankTotalBalance would be accessible only inside the constructor.

The program would not compile because getBankTotalBalance is static.

Each BankAccount would maintain its own bankTotalBalance value.

Explanation

This question tests understanding of class variables and methods in Java, specifically what happens when trying to access a non-static variable from a static method. Static methods cannot directly access instance variables because they don't have an implicit 'this' reference to any particular object. Choice A is correct because if bankTotalBalance were not static (making it an instance variable), the static method getBankTotalBalance() would not be able to access it directly, resulting in a compilation error. Choice C is incorrect in this context because while each account would have its own bankTotalBalance if it weren't static, the main issue is the compilation error that would occur first. To help students: Explain the rule that static methods can only directly access static variables. Use compiler error messages as teaching tools to show what happens when this rule is violated.

9

Which line of code demonstrates the use of a class method?


// ECommerceInventory tracks total sales using a class variable.

public class ECommerceInventory {

    // Class variable shared across all instances.

    private static int totalSales = 0;

    // Instance method updates the shared total.

    public void processSale(int itemsSold) {

        totalSales += itemsSold;

    }

    // Static method returns the shared total sales.

    public static int getTotalSales() {

        return totalSales;

    }

    // Main method demonstrates usage.

    public static void main(String[] args) {

        ECommerceInventory cart = new ECommerceInventory();

        cart.processSale(3);

        System.out.println(ECommerceInventory.getTotalSales());

    }

}

cart.processSale(3);

totalSales += itemsSold;

System.out.println(ECommerceInventory.getTotalSales());

ECommerceInventory cart = new ECommerceInventory();

Explanation

This question tests understanding of class variables and methods in Java, focusing on identifying static method calls in code. Static methods are called using the class name and can be identified by their declaration with the static keyword. Choice B is correct because ECommerceInventory.getTotalSales() demonstrates calling a static method using the class name, which is the standard way to invoke class methods in Java. Choice A is incorrect because processSale() is an instance method being called on the cart object, not a static method. To help students: Teach the naming convention where static methods are often called using ClassName.methodName() syntax. Practice identifying method declarations (static vs non-static) and matching them with their appropriate calling syntax.

10

How does the class variable affect the behavior of this code?


// Library uses a static class variable to represent total books available.

public class Library {

    // Class variable shared across all Library objects.

    private static int totalBooks = 0;

    // Constructor adds books to the shared total.

    public Library(int initialBooks) {

        totalBooks += initialBooks;

    }

    // Instance method checks out a book and updates the shared total.

    public void checkOutBook() {

        if (totalBooks > 0) {

            totalBooks--;

        }

    }

    // Static method returns the shared total.

    public static int getTotalBooks() {

        return totalBooks;

    }

    // Main method demonstrates shared state across instances.

    public static void main(String[] args) {

        Library l1 = new Library(1);

        Library l2 = new Library(1);

        l1.checkOutBook();

        System.out.println(Library.getTotalBooks());

    }

}

It restricts totalBooks so only main can read it.

It stores one totalBooks value shared by all Library objects.

It causes a runtime error when checkOutBook modifies totalBooks.

It makes totalBooks independent for l1 and l2 objects.

Explanation

This question tests understanding of class variables and methods in Java, specifically how static variables create shared state across all instances of a class. The static keyword makes totalBooks a class-level variable rather than an instance-level variable. Choice B is correct because the static totalBooks variable is shared by all Library objects - when l1 or l2 modifies it through their methods, they're modifying the same single variable that belongs to the Library class. Choice A is incorrect because it describes instance variable behavior; static variables are never independent per object but are always shared. To help students: Use memory diagrams showing one static variable box connected to multiple objects. Create examples where multiple objects read and write to the same static variable to demonstrate the shared nature clearly.