What this quiz covers
This quiz focuses on Class Variables And Methods, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
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());
}
}
AP Computer Science a Quiz
Practice Class Variables And Methods in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.
This quiz focuses on Class Variables And Methods, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
public class BankAccount { private static int totalAccounts = 0; private static double totalBalance = 0.0; private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
totalAccounts++;
totalBalance += initialBalance;
}
public static int getTotalAccounts() {
return totalAccounts;
}
public static double getAverageBalance() {
if (totalAccounts == 0) return 0.0;
return totalBalance / totalAccounts;
}
public void deposit(double amount) {
balance += amount;
totalBalance += amount;
}
}
Consider the BankAccount class shown above. If the following code is executed, what will be the value returned by BankAccount.getAverageBalance()?
BankAccount acc1 = new BankAccount(100.0); BankAccount acc2 = new BankAccount(200.0); acc1.deposit(50.0); BankAccount acc3 = new BankAccount(150.0);
public class GameSession { private static int totalSessions = 0; private static int totalScore = 0; private int sessionScore;
public GameSession() {
sessionScore = 0;
totalSessions++;
}
public void addPoints(int points) {
sessionScore += points;
totalScore += points;
}
public static double getAverageScore() {
if (totalSessions == 0) return 0.0;
return (double) totalScore / totalSessions;
}
public int getSessionScore() {
return sessionScore;
}
}
Which of the following statements about the GameSession class is most accurate regarding the relationship between class variables and instance methods?
public class Library { private static int totalBooks = 0; private static Library instance = null; private int booksInThisLocation;
private Library(int books) {
booksInThisLocation = books;
totalBooks += books;
}
public static Library getInstance(int books) {
if (instance == null) {
instance = new Library(books);
}
return instance;
}
public void addBooks(int books) {
booksInThisLocation += books;
totalBooks += books;
}
public static int getTotalBooks() {
return totalBooks;
}
}
What will be the value returned by Library.getTotalBooks() after executing the following code?
Library lib1 = Library.getInstance(100); Library lib2 = Library.getInstance(200); lib1.addBooks(50); lib2.addBooks(30);
public class Product { private static int nextProductId = 1; private static double totalValue = 0.0; private int productId; private double price;
public Product(double productPrice) {
productId = nextProductId++;
price = productPrice;
totalValue += price;
}
public void updatePrice(double newPrice) {
totalValue = totalValue - price + newPrice;
price = newPrice;
}
public static double getTotalValue() {
return totalValue;
}
public static void applyDiscount(double percentage) {
totalValue *= (1.0 - percentage / 100.0);
}
}
After executing the following code, what will be the approximate value returned by Product.getTotalValue()?
Product p1 = new Product(100.0); Product p2 = new Product(200.0); p1.updatePrice(150.0); Product.applyDiscount(10.0);
totalValue starts at 0.0. When Product p1 = new Product(100.0) executes, the constructor adds 100.0 to totalValue, making it 100.0. Next, Product p2 = new Product(200.0) adds 200.0 to totalValue, bringing it to 300.0.
The key step is p1.updatePrice(150.0). This method first subtracts the old price (100.0) from totalValue, then adds the new price (150.0). So totalValue becomes 300.0 - 100.0 + 150.0 = 350.0. Finally, Product.applyDiscount(10.0) multiplies totalValue by 0.9 (since 1.0 - 10.0/100.0 = 0.9), giving us 350.0 × 0.9 = 315.0.
Choice A (450.0) incorrectly adds all prices without accounting for the price update. Choice B (350.0) represents the total before applying the discount. Choice C (270.0) appears to apply the discount to the original total of 300.0, missing the price update effect.
When working with static variables that track cumulative data, always trace through each operation methodically. Pay special attention to update methods that both subtract old values and add new ones—these maintain the accuracy of your running totals.public class Inventory { private static int itemCount = 0; private static double totalValue = 0.0; private int quantity; private double unitPrice;
public Inventory(int qty, double price) {
quantity = qty;
unitPrice = price;
itemCount++;
totalValue += quantity * unitPrice;
}
public void restock(int additionalQty) {
quantity += additionalQty;
totalValue += additionalQty * unitPrice;
}
public void adjustPrice(double newPrice) {
totalValue = totalValue - (quantity * unitPrice) + (quantity * newPrice);
unitPrice = newPrice;
}
public static double getTotalValue() {
return totalValue;
}
}
Which statement best describes the behavior of the Inventory class methods when multiple instances interact with the class variables?
public class Course { private static int totalEnrollments = 0; private static Course[] allCourses = new Course[10]; private static int courseCount = 0; private int enrollment; private String courseName;
public Course(String name, int initialEnrollment) {
courseName = name;
enrollment = initialEnrollment;
totalEnrollments += enrollment;
if (courseCount < 10) {
allCourses[courseCount] = this;
courseCount++;
}
}
public static int getTotalEnrollments() {
return totalEnrollments;
}
public static int getAverageEnrollment() {
return courseCount > 0 ? totalEnrollments / courseCount : 0;
}
}
If five Course objects are created with enrollments of 25, 30, 35, 40, and 45 respectively, and then two more Course objects are created with enrollments of 20 and 50, what will be the return value of Course.getAverageEnrollment()?
totalEnrollments (sum of all enrollments), allCourses (array storing Course objects), and courseCount (number of courses created). Each time a Course is created, the constructor adds the enrollment to totalEnrollments and increments courseCount.
Creating five courses with enrollments 25, 30, 35, 40, and 45:
totalEnrollments = 25 + 30 + 35 + 40 + 45 = 175courseCount = 5totalEnrollments = 175 + 20 + 50 = 245courseCount = 7getAverageEnrollment() method returns totalEnrollments / courseCount = 245 / 7 = 35 (integer division).
Answer A (245) represents the total enrollments, not the average. Answer B (32) might result from incorrect integer division or miscounting courses. Answer D (29) could come from dividing by 8 instead of 7, perhaps mistakenly thinking the array size affects the calculation.
Remember that static variables persist throughout the program's execution and accumulate values across all object instantiations. When calculating averages in programming problems, pay close attention to integer division behavior in Java, which truncates decimal portions rather than rounding.public class Student { private static int nextId = 1000; private static int totalStudents = 0; private int studentId; private String name;
public Student(String studentName) {
studentId = nextId;
nextId++;
name = studentName;
totalStudents++;
}
public static int getNextId() {
return nextId;
}
public static void resetIdCounter() {
nextId = 1000;
}
public int getId() {
return studentId;
}
}
Consider the Student class shown above. After the following sequence of operations, what will be the values returned by s2.getId() and Student.getNextId(), respectively?
Student s1 = new Student("Alice"); Student s2 = new Student("Bob"); Student s3 = new Student("Carol"); Student.resetIdCounter(); Student s4 = new Student("David");
public class Counter { private static int globalCount = 0; private int instanceCount = 0;
public Counter() {
globalCount++;
instanceCount++;
}
public static void incrementGlobal() {
globalCount++;
}
public void incrementInstance() {
instanceCount++;
globalCount++;
}
public static int getGlobalCount() {
return globalCount;
}
public int getInstanceCount() {
return instanceCount;
}
}
Given the Counter class above, what will be printed by the following code?
Counter c1 = new Counter(); Counter c2 = new Counter(); Counter.incrementGlobal(); c1.incrementInstance(); c2.incrementInstance(); System.out.println(Counter.getGlobalCount() + " " + c1.getInstanceCount() + " " + c2.getInstanceCount());
public class Employee { private static int employeeCount = 0; private static double totalSalary = 0.0; private int empId; private double salary;
public Employee(double sal) {
empId = ++employeeCount;
salary = sal;
totalSalary += salary;
}
public static double getAverageSalary() {
return totalSalary / employeeCount;
}
public void giveRaise(double amount) {
salary += amount;
totalSalary += amount;
}
public static void layoff() {
employeeCount--;
}
}
What potential issue exists with the design of the Employee class regarding the interaction between instance methods and class variables?
layoff method creates a serious design flaw. When an employee is laid off, the method decreases employeeCount but leaves totalSalary unchanged. This means the laid-off employee's salary remains in the total, but they're no longer counted in the employee count. When getAverageSalary() calculates totalSalary / employeeCount, it will return an artificially inflated average since the denominator is smaller while the numerator still includes the departed employee's salary.
Option A is incorrect because starting employee IDs from 1 instead of 0 is actually a reasonable design choice and doesn't cause any functional problems. Option B misunderstands static methods—giveRaise should remain an instance method because it modifies both instance data (salary) and class data (totalSalary). Making it static would prevent access to the instance variable. Option D identifies a potential issue with division by zero, but this is a secondary concern compared to the fundamental data inconsistency in option C.
Study tip: When reviewing classes with static variables that track collective data (counts, totals, averages), always check that every method maintains consistency between related static variables. If one static variable changes, ask yourself whether other static variables should change too.