Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should toString() ever return null? [duplicate]

Should the method toString() in java ever return null if no conversion could be done or should it return an empty string in that case instead?

like image 655
craftxbox Avatar asked Jan 03 '23 11:01

craftxbox


1 Answers

null is not String so it is not allowed to return here. Check Java Docs:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

it should return a meaningful string representation of the object. I wrote an example of how to use it and why it is useful:

public class Car {
    private String make;
    private int year;
    public Car(String make, int year) {
        this.make = make;
        this.year = year;
    }    

    @Overrride
    public String toString() {
        return "Car Make:" + make + "; Built Year: " + year;
    }
}

Example:

Car myCar = new Car("Nissan", 1999);
Car yourCar = new Car("BMW", 2018);
System.out.println(myCar);  // call toString() implicitly
System.out.println(yourCar);

It will print 2 lines and you can easily read the text and know which is your car!

Car Make:Nissan; Built Year: 1999
Car Make:BMW; Built Year: 2018
like image 85
Haifeng Zhang Avatar answered Jan 05 '23 00:01

Haifeng Zhang