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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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());
}
}
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.
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);
Explanation: The correct answer is B. After creating acc1 (100.0), totalBalance = 100.0, totalAccounts = 1. After creating acc2 (200.0), totalBalance = 300.0, totalAccounts = 2. After acc1.deposit(50.0), totalBalance = 350.0, totalAccounts = 2. After creating acc3 (150.0), totalBalance = 500.0, totalAccounts = 3. The average is 500.0 / 3 = 166.67. Choice A incorrectly uses only the initial balances (450/3). Choice C incorrectly excludes the deposit (450/3 but wrong calculation). Choice D incorrectly returns the total balance instead of average.
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?
Explanation: The correct answer is A. The addPoints method properly updates both the instance variable sessionScore and the static variable totalScore, which allows getAverageScore to calculate the correct average score per session. Choice B is incorrect because dividing by total sessions created is the intended behavior for average score per session. Choice C is incorrect because it's perfectly valid and often necessary for instance methods to update static variables when tracking aggregate data. Choice D is incorrect because sessionScore should remain an instance variable to track individual session scores.
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);
Explanation: The correct answer is A. This implements a singleton pattern. Library.getInstance(100) creates the first (and only) instance with 100 books, so totalBooks = 100. Library.getInstance(200) returns the same instance (lib1), ignoring the parameter 200. lib1.addBooks(50) adds 50 to totalBooks, making it 150. lib2.addBooks(30) operates on the same object as lib1, adding 30 more, making totalBooks = 180. Choice B incorrectly assumes both getInstance calls create separate instances. Choice C misses the second addBooks call. Choice D miscalculates the additions.
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);
Explanation: This question tests your understanding of static variables and how they track data across multiple object instances. When you see static variables in a class, think about how they maintain shared state that persists through all operations on any instance of that class.
Let's trace through the code execution step by step. Initially, 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?
Explanation: The correct answer is D. The restock method correctly adds the value of additional quantity (additionalQty * unitPrice) to totalValue. The adjustPrice method correctly updates totalValue by subtracting the old total value for this item (quantity * old unitPrice) and adding the new total value (quantity * newPrice). Choice A is partially correct but doesn't fully describe adjustPrice. Choice B incorrectly suggests adjustPrice shouldn't add new value. Choice C incorrectly suggests restock fails to update totalValue.
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()?
Explanation: When you encounter questions about static variables and methods in Java, focus on how these class-level elements are shared across all instances and track cumulative data.
Let's trace through the Course object creation. The class maintains three static variables: 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:
Adding two more courses with enrollments 20 and 50:
totalEnrollments = 25 + 30 + 35 + 40 + 45 = 175courseCount = 5
The totalEnrollments = 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");
Explanation: The correct answer is B. When s1 is created, studentId = 1000, nextId becomes 1001. When s2 is created, studentId = 1001, nextId becomes 1002. When s3 is created, studentId = 1002, nextId becomes 1003. resetIdCounter() sets nextId back to 1000. When s4 is created, studentId = 1000, nextId becomes 1001. So s2.getId() returns 1001 (unchanged by reset) and Student.getNextId() returns 1001. Choice A incorrectly thinks getNextId() returns 1000. Choice C incorrectly thinks s2's ID changed. Choice D incorrectly thinks nextId continues from 1003.
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());
Explanation: The correct answer is A. Initially globalCount = 0. Creating c1: globalCount = 1, c1.instanceCount = 1. Creating c2: globalCount = 2, c2.instanceCount = 1. incrementGlobal(): globalCount = 3. c1.incrementInstance(): globalCount = 4, c1.instanceCount = 2. c2.incrementInstance(): globalCount = 5, c2.instanceCount = 2. Final values: globalCount = 5, c1.instanceCount = 2, c2.instanceCount = 2. Choice B incorrectly adds extra increments. Choice C incorrectly thinks c1.instanceCount becomes 3. Choice D miscounts the global increments.
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?
Explanation: When analyzing class design with static variables, you need to consider how all methods that modify those variables maintain data consistency. Static variables belong to the class itself and track information across all instances.
The correct answer is C because the 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.