LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 18

Finding the oldest person in an array of objects Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links