Avatar ·

How to avoid null checks in Java: best practices and alternatives

Hello everyone! I'm a beginner Java developer, and I'm struggling with one problem. In my code, I constantly have to write null checks, and it looks terrible. For example, I have a method that gets a User object from the database, and if it's not null, I want to get its name. But if the object is null, everything crashes with a NullPointerException. Here's how I'm doing it now:
public String getUserName(User user) {
    if (user != null) {
        return user.getName();
    }
    return "Unknown";
}
And then, when I need to get a name from nested objects, it gets even worse:
public String getCityName(User user) {
    if (user != null) {
        Address address = user.getAddress();
        if (address != null) {
            City city = address.getCity