X754: Null Pointer Exception Practice 3

For the question below, assume the following implementation of a Person class:

public class Person {
    private int age;
    private String name;
    private String grade;

    public Person(int a, String n, String gr) {
        age = a;
        name = n;
        grade = gr;
    }


    public int getAge() {
        return age;
    }


    public String getName() {
        return name;
    }


    public String getGrade() {
        return grade;
    }

}

Your coworker now wants to create a method that will take in 3 person objects as parameters and return oldest Person. However, this code is failing if one (or more) of the parameters equals null.

If one of the parameters is null, the program should return the oldest all non-null people. If all three are null, the method should return null.

For example, if the following people were passed as parameters:

  • Anne, age 15, grade B
  • null
  • Ben, age 10, grade F

then the method would return Anne.

Fix the issue with the code think about how you would explain the problem to your coworker.

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.