Question 18
Back to Exercise
What is the output of the following Java program?
class Person {
String name;
int age;
Person(String n, int a) { name = n; age = a; }
}
public class Main {
public static void main(String[] args) {
Person[] people = {new Person("Asha", 21), new Person("Ravi", 34), new Person("Meena", 29)};
Person oldest = people[0];
int totalAge = 0;
for (Person p : people) {
if (p.age > oldest.age) oldest = p;
totalAge += p.age;
}
System.out.println(oldest.name + " " + totalAge / people.length);
}
}
- A Ravi 28 Correct
- B Asha 28
- C Ravi 84
- D Meena 28
Correct Answer: Option A
oldest is a reference that moves to whichever object has the largest age; (21 + 34 + 29) / 3 = 28.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!