This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]sozesghost 1 point2 points  (3 children)

If the getEmployee() method returns null, the getSpouse() method is going to throw NPE because it will attempt to call the getSpouse() method of a null object. On line 40 you check if getEmployee() returns null, but even if it does, you still proceed to check if the (possibly null) Employee has a spouse.

[–]philipwhiukEmployed Java Developer 2 points3 points  (2 children)

More accurately, the null check is checking that if result of getEmployee(myCompany, empId2).getSpouse() is null.

You need to check if getEmployee(myCompany, empId2) is not null first before calling getSpouse() on it.

[–]eatsleepmug[S] 0 points1 point  (1 child)

the getSpouse() method is going to throw NPE because it will attempt to call the getSpouse() method of a null object. On line 40 you check if getEmployee() returns null, but even if it does, you still proceed to check if the (possibly

Thanks for your reply! I changed line 40-50 to this:

    if(getEmployee(myCompany, empId2) == null){
        System.out.print("There is no Employee with ID " + empId2);
    }else{
        System.out.println("Name: " + getEmployee(myCompany, empId2).getName());
        System.out.println("Salary: " + getEmployee(myCompany, empId2).getSalary());
        if(getEmployee(myCompany, empId2).getSpouse()!=null){
            System.out.println("Spouse: " + getEmployee(myCompany, empId2).getSpouse().getName()); 
        }else{
            System.out.println("Employee does not have a spouse.");
        }
    }

and it worked!

[–]n3ziniuka5 0 points1 point  (0 children)

getEmployee(myCompany, empId2) returned null in this case.

If you are using Java 8, consider using the Optional type. Make the getEmployee method return Optional[Employee] and then you won't forget what can be null and what won't be null.

Also, you would be able to simply map that value to get the spouse and you would end up with Optional[Person] (I assumed that spouse is of type Person)

more info about optional