?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

Search for Strings in an Array of Objects

APCSA-DETYWE

Consider the following class.

public class Baby 
{
    private String firstName;
    private String lastName;
    private double weight;
    private String gender;  // M or F

    public Baby(String firstName, String lastName, double weight, String gender)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.weight = weight;
        this.gender = gender;  // M or F
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getLastName()
    {
        return lastName;
    }

    public String getFullName()
    {
        return firstName + " " + lastName;
    }

    public double getWeight()
    {
        return weight;
    }

    // other data and methods not shown    
}

Given an array of Baby objects, and the first and last name of the baby to search for, which of the following methods will search for the baby and return the Baby object if found or return null if the baby was not found?

A
public static String findBaby(Baby[] babies, String fName, String lName)
{
    for (Baby b : babies)
    {
        if (b.getFirstName().equals(fName) && b.getLastName().equals(lName))
            return b.getFullName();
    }
    return null;
}
B
public static Baby findBaby(Baby[] babies, String fName, String lName)
{
    for (int i=0; i<babies.length; i++)
    {
        if (babies.get(i).getFirstName().equals(fName) && babies.get(i).getLastName().equals(lName))
            return b.getFullName();
    }
    return null;
}
C
public static Baby findBaby(Baby[] babies, String fName, String lName)
{
    for (Baby b : babies)
    {
        if (b.getFirstName().equals(fName) && b.getLastName().equals(lName))
            return b;
    }
    return null;
}
D
public static Baby findBaby(Baby[] babies, String fName, String lName)
{
    for (int i=0; i<babies.length; i++)
    {
        if (babies.get(i).getFirstName().equals(fName) && babies.get(i).getLastName().equals(lName))
            return babies;
    }
    return null;
}
E
public static Baby findBaby(Baby[] babies, String fName, String lName)
{
    for (int i=0; i<babies.length; i++)
    {
        if (babies.get(i).getFirstName().equals(fName) && babies.get(i).getLastName().equals(lName))
        {
            return babies.get(i);
            break;
        }
    }
    return null;
}