Search code examples
javastringnulltostring

Java toString() How to return String message in place of null


How can I print an "error" String message in a field that returns null? Here's what I'm trying to do:
When passed an animal object, the toString() method should return a string that looks like this.

Name: "fluffy"
Breed: Pitbull
Age: Data not available

As you can see from the above example the string contains a label for each field, followed by a colon and the data stored in that field. I'm able to print the String like the example below (Notice that Age is missing data because it's null).

Name: "fluffy"
Breed: Pitbull
Age: 

I've written the toString() method like this

    public String toString() {
        return "\n" +
                "\nName: " + this.name +
                "\nBreed: " + this.breed +
                "\nAge: " + this.age +
                "\n";
}

When the field is null or empty, I want the data to be replaced with a "No Data available" message.

I've tried using conditional statements

@Override
    public String toString() {
    String errorMessage = "Data not available";
        if (name == null){
            System.out.println(errorMessage);
        }
        if (breed == null){
            System.out.println(errorMessage);
        }...

I've also tried looping through with a for each

    @Override
    public String toString() {
      for (String field: fields)
            if (field != null) {
        return "\n" +
                "\nName: " + this.name +
                  "\nBreed: " + this.breed +
                  "\nAge: " + this.age +
                  "\n";
    }
}
            } else (field == null){
                return "Data not available";
            }

I've looked at other feeds on here but still don't quite understand how to ensure that each field if null gets the error message. Here's a list of the posts that I've reviewed on StackOverflow: Returning a string with toString java ,
java toString() is returning null from class , java toString() returning this

Thanks in advance for your help! I'm new to coding and I really appreciate all the people who have helped me understand along the way.


Solution

  • class Dog {
    
        private static final String DEFAULT_MESSAGE = "No Data Available";
    
        private final String name;
    
        private final String breed;
    
        private final Integer age;
    
        public Dog(String name, String breed, Integer age) {
            this.name = name;
            this.breed = breed;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return String.format("name=%s\nbreed=%s\nage=%s",
                    name == null ? DEFAULT_MESSAGE : name,
                    breed == null ? DEFAULT_MESSAGE : breed,
                    age == null ? DEFAULT_MESSAGE : age);
        }
    }