#### Question

# AP Comp Science Java Help?

Using this:

public static Person test( Person[] r )

{

if ( r.length == 0 )

return null;

Person a = r[ 0 ];

for ( Person p : r )

{

if ( p.getAge() > a.getAge() )

a = p;

}

return a;

}

If x is an array of Person objects such that the length of x is at least 1, and if no two Person objects in x have the same age, then the value of test( x ) is

A. the age of x[ 0 ].

B. the age of the oldest Person object in x.

C. the first Person object in x with an age greater than 0.

D. the last Person object in x with an age greater than 0.

E. the oldest Person object in x.

#### Answers

I've commented every line as best I could:

public static Person test( Person[] r ) //method declaration

{

if ( r.length == 0 ) //if the length of passed array is 0

return null; //return null, exit method

Person a = r[ 0 ]; //new person object reference 'a' points to new person object same as first array element at 0

for ( Person p : r ) //for-each loop iterating through array of person objects, using 'p' as the 'current' person object in each iterate

{

if ( p.getAge() > a.getAge() ) //if the age of 'p' is greater than the age of 'a'

a = p; //Person object reference at 'a' now points to greater 'p' person object

} //this loop iterates through Person object array, with the Person object with the greatest getAge() value being referenced from 'a' eventually.

return a; //return 'a' Person object, the oldest Person object

}

So in essence E. the oldest Person object in x is returned

E.

It should return the oldest Person object in x.

Hope that helps.

=D