This might be a very basic question, apologies if this was already asked. Should toString() in Java be used for actual program logic or is it only for debugging/human reading only. My basic question is should be using toString() or write a different method called asString() when I need to use the string representation in the actual program flow.
The reason I ask is I have a bunch of classes in a web service that rely on a toString() to work correctly, in my opinion something like asString() would have been safer.
Thanks
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.
Every class in Java inherits the default implementation of the toString method. The functionality of the toString method is to return a String representation of the object on which it's called.
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.
This is how every class has a toString() method: since Object has a toString() method, then 'children' of Object inherit a toString() method, the children of children of Object inherit a toString() method, and so on. So every class 'automatically' gets a toString() method by inheritance.
Except for a few specific cases, the toString
should be used for debugging, not for the production flow of data.
The method has several limitations which make it less suitable for use in production data flow:
java.Object
class, this method is commonly overridden by subclasses. This may be harmful in situations when you depend on the particular representation, because the writers of the subclass may have no idea of your restrictions.The obvious exceptions to this rule are toString
methods of the StringBuilder
and the StringBuffer
classes, because these two methods simply make an immutable string from the mutable content of the corresponding object.
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