What this quiz covers
This quiz focuses on Methods Passing And Returning References, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.
Based on the code snippet above, what is returned by the method deposit? Describe its significance.
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Adds funds to this account
public void deposit(double amount) {
balance += amount;
}
// Deposits then returns this same account reference
public BankAccount depositAndReturn(double amount) {
deposit(amount);
return this;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acct = new BankAccount("A100", 50.0);
BankAccount ref = acct.depositAndReturn(25.0);
System.out.println(acct.getBalance());
System.out.println(ref.getBalance());
}
}
AP Computer Science a Quiz
Practice Methods Passing And Returning References 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 Methods Passing And Returning References, 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.
Based on the code snippet above, what is returned by the method deposit? Describe its significance.
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Adds funds to this account
public void deposit(double amount) {
balance += amount;
}
// Deposits then returns this same account reference
public BankAccount depositAndReturn(double amount) {
deposit(amount);
return this;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acct = new BankAccount("A100", 50.0);
BankAccount ref = acct.depositAndReturn(25.0);
System.out.println(acct.getBalance());
System.out.println(ref.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, the 'this' keyword refers to the current object instance, and returning 'this' from a method returns a reference to that same object, enabling method chaining. In this scenario, the depositAndReturn method first calls deposit to add funds, then returns 'this' - a reference to the current BankAccount object that was just modified. Choice C is correct because it identifies that the method returns a reference to the same modified BankAccount object, allowing the caller to continue working with the updated object through the returned reference. Choice A is incorrect because it suggests a new object is created and returned, which doesn't happen - the same object reference is returned after modification. To help students: Demonstrate method chaining with visual representations of how 'this' points to the current object. Show examples where returning 'this' enables fluent interfaces like builder patterns.
Based on the code snippet above, which describes the state of acct after depositAndReturn executes?
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Adds funds to this account
public void deposit(double amount) {
balance += amount;
}
// Deposits then returns this same account reference
public BankAccount depositAndReturn(double amount) {
deposit(amount);
return this;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acct = new BankAccount("A200", 100.0);
BankAccount ref = acct.depositAndReturn(40.0);
ref.deposit(10.0);
System.out.println(acct.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, when a method returns 'this', it returns a reference to the same object, meaning multiple variables can reference the same object in memory. In this scenario, acct starts with balance 100.0, depositAndReturn adds 40.0 (making it 140.0) and returns 'this' to ref, then ref.deposit(10.0) adds another 10.0 to the same object, resulting in a final balance of 150.0. Choice C is correct because both acct and ref reference the same BankAccount object in memory - any modifications through either reference affect the same object, so the balance becomes 150.0 after both deposits. Choice B is incorrect because it fails to account for the second deposit through ref, missing that both variables point to the same object. To help students: Use box-and-arrow diagrams to show how multiple references can point to the same object. Trace through the code step-by-step, updating the object's state to show cumulative effects.
Based on the code snippet above, which describes the state of acct after tryReassign executes?
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Adds funds to this account
public void deposit(double amount) {
balance += amount;
}
// Attempts to reassign the parameter to a new object
public static void tryReassign(BankAccount target) {
target = new BankAccount("NEW", 999.0);
target.deposit(1.0);
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acct = new BankAccount("A500", 10.0);
tryReassign(acct);
System.out.println(acct.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, reassigning a parameter reference inside a method only affects the local parameter variable, not the original reference passed from the caller. In this scenario, tryReassign receives a copy of the reference to acct, but when it reassigns target to a new BankAccount object, only the local parameter target is changed - the original acct reference remains unchanged and still points to the original object with balance 10.0. Choice B is correct because reassigning the parameter target doesn't affect the caller's reference acct - the reassignment is local to the method, so acct still references the original object with balance 10.0. Choice A is incorrect because it assumes reassigning a parameter can change the caller's reference, which is impossible in Java since references are passed by value. To help students: Emphasize that Java is always pass-by-value, including for references - the value being passed is the reference itself. Use diagrams to show how reassigning a parameter creates a new arrow from the parameter to a different object, leaving the original reference unchanged.
In the provided class example, what will be the output after calling the method depositAndReturn?
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Adds funds to this account
public void deposit(double amount) {
balance += amount;
}
// Deposits then returns this same account reference
public BankAccount depositAndReturn(double amount) {
deposit(amount);
return this;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acct = new BankAccount("A600", 5.0);
BankAccount ref = acct.depositAndReturn(2.5);
ref.deposit(1.5);
System.out.println(acct.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, when a method returns 'this', it enables multiple operations on the same object, and all references to that object see the cumulative changes. In this scenario, acct starts with balance 5.0, depositAndReturn adds 2.5 (making it 7.5) and assigns the returned reference to ref, then ref.deposit(1.5) adds another 1.5 to the same object, resulting in a final balance of 9.0. Choice C is correct because both acct and ref reference the same BankAccount object - the first deposit increases the balance to 7.5, and the second deposit through ref increases it further to 9.0, which is displayed when accessing the balance through acct. Choice B is incorrect because it only accounts for the first deposit, missing that the second deposit also affects the same object since ref and acct point to the same instance. To help students: Trace the execution step-by-step, showing the balance after each operation. Emphasize that returning 'this' doesn't create a new object but provides another way to reference the same object.
Based on the code snippet above, which describes the state of a and b after transferTo executes?
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Moves money from this account into another account
public BankAccount transferTo(BankAccount other, double amount) {
this.balance -= amount;
other.balance += amount;
return other;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount a = new BankAccount("A", 50.0);
BankAccount b = new BankAccount("B", 10.0);
a.transferTo(b, 15.0);
System.out.println(a.getBalance() + "," + b.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, methods can modify multiple objects when given references to them, and changes to object state through any valid reference are permanent. In this scenario, transferTo is called on object a, which decreases a's balance by 15.0 (from 50.0 to 35.0) and increases b's balance by 15.0 (from 10.0 to 25.0), effectively transferring funds between the two accounts. Choice B is correct because both referenced objects were mutated - the method modifies this.balance (object a) by subtracting the amount and other.balance (object b) by adding the amount, resulting in balances of 35.0 and 25.0 respectively. Choice A is incorrect because it claims objects are passed by value in a way that prevents modification, but Java passes references by value, allowing methods to modify the objects those references point to. To help students: Step through the code showing how 'this' refers to object a and 'other' refers to object b. Use visual representations of bank accounts with arrows showing money movement to make the transfer concept concrete.
In the provided class example, what is returned by the method transferTo? Describe its significance.
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Moves money from this account into another account
public BankAccount transferTo(BankAccount other, double amount) {
this.balance -= amount;
other.balance += amount;
return other;
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount a = new BankAccount("A", 80.0);
BankAccount b = new BankAccount("B", 20.0);
BankAccount result = a.transferTo(b, 30.0);
System.out.println(result.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, methods can modify multiple objects through their references and return any reference, enabling flexible object interactions and method chaining. In this scenario, transferTo modifies both the calling object (this) by decreasing its balance and the parameter object (other) by increasing its balance, then returns the reference to other, which now has balance 50.0 (20.0 + 30.0). Choice A is correct because the method returns a reference to the other account after transferring funds to it, enabling continued operations on the recipient account - this design allows for chaining operations on the account that received the transfer. Choice B is incorrect because methods don't automatically return the caller object - the explicit 'return other' statement determines what reference is returned. To help students: Trace through the method showing how both objects are modified and how the return value is determined. Demonstrate practical uses of returning specific object references for method chaining and fluent interfaces.
Based on the code snippet above, how does the method deposit affect the object passed as target?
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
// Adds funds to this account
public void deposit(double amount) {
balance += amount;
}
// Helper method: passes an object reference into a method
public static void applyDeposit(BankAccount target, double amount) {
target.deposit(amount);
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankAccount acct = new BankAccount("A400", 60.0);
applyDeposit(acct, 15.0);
System.out.println(acct.getBalance());
}
}
Explanation: This question tests AP Computer Science A skills: understanding methods passing and returning object references. In Java, when an object reference is passed as a parameter, the method receives a copy of the reference value, but this copy still points to the same object in memory. In this scenario, applyDeposit receives a reference to the same BankAccount object that acct references, and calling target.deposit(amount) modifies the balance of that shared object from 60.0 to 75.0. Choice A is correct because the method changes the balance field of the object that both target and acct reference - since they point to the same object in memory, the change is visible through the acct reference. Choice B is incorrect because it suggests only a copy is modified, misunderstanding that while the reference is copied, both references point to the same mutable object. To help students: Draw diagrams showing how parameter passing creates a new reference variable that points to the same object. Demonstrate that modifications through any reference to an object are visible through all references to that object.
public class Rectangle { private int width, height;
public Rectangle(int w, int h) {
width = w;
height = h;
}
public void scale(double factor) {
width = (int)(width * factor);
height = (int)(height * factor);
}
public Rectangle clone() {
return new Rectangle(width, height);
}
public int getArea() {
return width * height;
}
}
public class RectangleUtils { public static Rectangle resize(Rectangle r, double factor) { if (factor == 1.0) { return r; } else if (factor > 1.0) { r.scale(factor); return r; } else { Rectangle copy = r.clone(); copy.scale(factor); return copy; } } }
Consider this code execution:
Rectangle rect1 = new Rectangle(10, 8); Rectangle rect2 = new Rectangle(10, 8); Rectangle rect3 = new Rectangle(10, 8); Rectangle result1 = RectangleUtils.resize(rect1, 1.0); Rectangle result2 = RectangleUtils.resize(rect2, 2.0); Rectangle result3 = RectangleUtils.resize(rect3, 0.5);
Which rectangles have been modified from their original dimensions?
Explanation: When you encounter questions about object modification and method calls, focus on whether methods modify the original object or create new copies, and trace through each code path carefully.
Let's analyze what happens to each rectangle through the resize method:
For rect1 with factor 1.0: The condition factor == 1.0 is true, so the method simply returns r (the original rectangle) without any modifications. The original rect1 keeps its 10×8 dimensions.
For rect2 with factor 2.0: Since 2.0 > 1.0, the method calls r.scale(factor) directly on the original rectangle, then returns it. The scale method modifies rect2's width and height in place, changing them to 20×16. The original rect2 is permanently modified.
For rect3 with factor 0.5: Since 0.5 < 1.0, the method creates a copy using r.clone(), then calls scale on that copy. The original rect3 remains unchanged at 10×8, while only the copy gets modified to 5×4.
Answer choice A incorrectly claims rect3 was modified, but the scaling happened to its clone. Answer choice B wrongly states rect1 was modified, when it was returned unchanged. Answer choice D incorrectly suggests all rectangles were modified.
Only answer choice C correctly identifies that solely rect2 was modified from its original dimensions.
Study tip: When tracing object modifications, always distinguish between methods that modify the original object versus those that work on copies. Pay special attention to conditional logic that determines which path executes.
public class Student { private String name; private int grade;
public Student(String n, int g) {
name = n;
grade = g;
}
public void setGrade(int g) {
grade = g;
}
public int getGrade() {
return grade;
}
public String getName() {
return name;
}
}
public class ClassRoom { public static Student updateStudent(Student s) { s.setGrade(s.getGrade() + 10); s = new Student("Updated", 100); return s; }
public static void main(String[] args) {
Student alice = new Student("Alice", 85);
Student result = updateStudent(alice);
System.out.println(alice.getName() + ": " + alice.getGrade());
System.out.println(result.getName() + ": " + result.getGrade());
}
}
What is the output when the main method is executed?
Explanation: When alice is passed to updateStudent(), the reference is copied. First, s.setGrade(95) modifies the original alice object through the reference. Then s is reassigned to point to a new Student object, but this doesn't affect the original alice reference. The method returns the new Student object. Output: Alice: 95, Updated: 100.
public class Box { private int value;
public Box(int v) {
value = v;
}
public void setValue(int v) {
value = v;
}
public int getValue() {
return value;
}
}
public class BoxProcessor { public static Box processBox(Box original) { if (original.getValue() > 50) { original.setValue(original.getValue() * 2); return original; } else { return new Box(original.getValue() + 25); } } }
Consider the following code segment:
Box box1 = new Box(30); Box box2 = new Box(60); Box result1 = BoxProcessor.processBox(box1); Box result2 = BoxProcessor.processBox(box2);
After this code executes, which statement is true?
Explanation: For box1 (value 30): Since 30 ≤ 50, processBox creates and returns a new Box object with value 55. For box2 (value 60): Since 60 > 50, processBox modifies the original object (setting value to 120) and returns the same reference. Therefore, result1 and box1 are different objects, while result2 and box2 are the same object.
public class Counter { private int count;
public Counter(int c) {
count = c;
}
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class CounterUtils { public static Counter doubleCounter(Counter c) { c.increment(); Counter newCounter = new Counter(c.getCount() * 2); c = newCounter; return c; } }
What will be the values of original.getCount() and result.getCount() after executing the following code?
Counter original = new Counter(5); Counter result = CounterUtils.doubleCounter(original);
Explanation: In doubleCounter(), the parameter c initially refers to the same object as original. c.increment() modifies the original object (count becomes 6). A new Counter is created with value 12 (6 * 2). The local variable c is reassigned to this new object and returned. The original object retains its modified value of 6, while result references the new object with value 12.
public class Account { private double balance; private String owner;
public Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public String getOwner() {
return owner;
}
}
public class BankUtils { public static Account transfer(Account from, Account to, double amount) { from.deposit(-amount); to.deposit(amount); if (from.getBalance() < 0) { return new Account(from.getOwner(), 0); } return from; } }
What happens when this code executes?
Account acc1 = new Account("Alice", 100.0); Account acc2 = new Account("Bob", 50.0); Account result = BankUtils.transfer(acc1, acc2, 150.0);
Explanation: When you encounter questions about object references and method calls that modify objects, you need to carefully trace how the original objects change and what new objects might be created.
Let's trace through the transfer method step by step. Starting with acc1 (Alice, $100) and acc2 (Bob, $50), we're transferring $150 from acc1 to acc2.
First, from.deposit(-amount) calls acc1.deposit(-150), which subtracts 150 from acc1's balance: 100 + (-150) = -50. So acc1's balance becomes -50.0. Next, to.deposit(amount) adds 150 to acc2's balance: 50 + 150 = 200. The crucial part is the conditional check: since from.getBalance() returns -50.0, which is less than 0, the method executes return new Account(from.getOwner(), 0). This creates a completely new Account object with Alice's name and a 0 balance.
Answer choice A incorrectly assumes the method returns the original acc1 object when the balance goes negative. Answer choice B wrongly suggests that acc1's balance itself gets reset to 0, but the original object remains at -50.0. Answer choice C mistakenly claims acc1's balance doesn't change, but the deposit method definitely modifies the original object's balance.
The correct answer is D: acc1's balance becomes -50.0 (the original object is modified), while result references a new Account object with balance 0.0.
Key strategy: Always distinguish between modifying an existing object's state versus creating and returning a new object. The original objects can still change even when methods return new objects.
public class Node { private int data; private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
public void setNext(Node next) {
this.next = next;
}
public Node getNext() {
return next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
public class NodeProcessor { public static Node processNodes(Node head) { Node current = head; while (current != null && current.getNext() != null) { current.setData(current.getData() + current.getNext().getData()); current = current.getNext().getNext(); } return head; } }
Consider a linked list: node1(5) -> node2(3) -> node3(7) -> node4(2) -> null
After calling NodeProcessor.processNodes(node1), what are the data values in the nodes?
Explanation: When you encounter linked list traversal problems, focus on carefully tracking how the loop variable advances and which nodes get modified. This question tests your ability to trace through a while loop that processes every other node.
Let's trace through processNodes step by step. The method starts with current pointing to node1(5). The while loop continues as long as current isn't null AND current.getNext() isn't null.
First iteration: current points to node1(5). Since node1 exists and has a next node (node2), we enter the loop. We update node1's data: 5 + 3 = 8. Then current advances by TWO positions to node3(7).
Second iteration: current points to node3(7). Since node3 exists and has a next node (node4), we continue. We update node3's data: 7 + 2 = 9. Then current advances by TWO positions to null (beyond node4).
Loop ends: current is null, so the condition fails.
The key insight is that current = current.getNext().getNext() skips every other node, so only nodes at odd positions (1st, 3rd, etc.) get their data modified.
Choice A incorrectly assumes only the first node changes. Choice B mistakenly thinks node2 also gets modified and that changes cascade through the list. Choice C wrongly believes node2 and node4 get updated instead of node1 and node3.
Study tip: When tracing linked list algorithms, draw out the nodes and carefully track which pointer moves where after each iteration. Pay special attention to how many positions the loop variable advances—it's often more than one!
public class Point { private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public Point copy() {
return new Point(x, y);
}
public int getX() { return x; }
public int getY() { return y; }
}
public class PointProcessor { public static Point processPoint(Point p, boolean shouldCopy) { if (shouldCopy) { Point temp = p.copy(); temp.move(5, 5); return temp; } else { p.move(5, 5); return p; } } }
Consider this code segment:
Point p1 = new Point(10, 20); Point p2 = new Point(10, 20); Point result1 = PointProcessor.processPoint(p1, true); Point result2 = PointProcessor.processPoint(p2, false);
Which statement correctly describes the final state?
Explanation: For p1 with shouldCopy=true: A copy is made and moved to (15, 25), original p1 remains (10, 20), result1 references the copy. For p2 with shouldCopy=false: The original p2 is moved to (15, 25) and returned, so result2 and p2 reference the same object. Final state: p1(10, 20), p2(15, 25), result1 and p1 are different objects.
public class Card { private String suit; private int value;
public Card(String suit, int value) {
this.suit = suit;
this.value = value;
}
public void setValue(int v) {
value = v;
}
public int getValue() {
return value;
}
public String getSuit() {
return suit;
}
}
public class CardGame { public static Card playCard(Card card, boolean isSpecialRound) { card.setValue(card.getValue() + 1); if (isSpecialRound && card.getValue() > 10) { return new Card(card.getSuit(), 1); } if (!isSpecialRound && card.getValue() == 11) { card.setValue(1); } return card; } }
Consider this sequence of method calls:
Card card1 = new Card("Hearts", 10); Card card2 = new Card("Spades", 10); Card result1 = CardGame.playCard(card1, true); Card result2 = CardGame.playCard(card2, false);
What are the final values and object relationships?
Explanation: When you encounter questions about object references and method calls, you need to carefully trace through the code execution while tracking both the values of object fields and whether methods return the same object or create new ones.
Let's trace through each method call step by step. For CardGame.playCard(card1, true) where card1 starts with value 10: First, the method increments card1's value to 11. Since isSpecialRound is true and the value (11) is greater than 10, the method creates and returns a new Card object with suit "Hearts" and value 1. The original card1 still exists with its modified value of 11.
For CardGame.playCard(card2, false) where card2 starts with value 10: The method increments card2's value to 11. Since isSpecialRound is false, we skip the first if-statement. The second condition checks if the value equals 11, which it does, so the method calls setValue(1) on card2 itself, changing its value to 1. The method then returns card2 (the same object).
Therefore, card1 has value 11, card2 has value 1, and result1 is a different object from card1.
Choice A incorrectly states card1's value is 1 and that result1 and card1 are the same object. Choice B incorrectly claims card2's value is 11 and that result1 and card1 are different objects (the relationship is wrong). Choice D incorrectly states that result1 and card1 are the same object.
Remember: when a method returns new ClassName(), it creates a different object; when it returns the parameter directly, it's the same object reference.