2012 AP CSA FRQ 2: HorseBarn - Solution

2012 AP CSA FRQ 2: HorseBarn

Topic: Arrays & Consolidation

Skills: Array traversal, null handling, consolidation algorithm

Unit: Unit 4 (Data Collections) (2025-2026 AP CSA)

Points: 9 | Time: ~22 minutes

Part (a)

Write the findHorseSpace method that finds a horse by name.

Try First! Attempt before viewing solution.

Solution

public int findHorseSpace(String name)
{
    for (int i = 0; i < spaces.length; i++)
    {
        if (spaces[i] != null && spaces[i].getName().equals(name))
        {
            return i;
        }
    }
    return -1;
}

Part (b)

Write the consolidate method that moves all horses to the front.

Solution

public void consolidate()
{
    Horse[] newSpaces = new Horse[spaces.length];
    int index = 0;
    
    for (int i = 0; i < spaces.length; i++)
    {
        if (spaces[i] != null)
        {
            newSpaces[index] = spaces[i];
            index++;
        }
    }
    spaces = newSpaces;
}

Key Concepts

✓ Check for null before calling methods on objects
✓ Use equals() for String comparison
✓ Consolidation: copy non-null to new array sequentially
✓ Return -1 for not found

Common Mistakes

NullPointerException from not checking null first
Using == instead of equals() for name comparison
Not preserving order during consolidation
Forgetting to assign new array to instance variable

Official Resources

Author: Tanner Crow - AP CS Teacher, 11+ years

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]