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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With