I am not clear with tostring method can someone please explain it for me | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I am not clear with tostring method can someone please explain it for me

Core java

9th Apr 2019, 8:41 AM
akshay patel
6 Answers
+ 10
▪toString() Methods Print methods are common in some languages, but most Java programs operate differently. You can use System.out.println() to print any object. However for good results your class should have a toString() method that formats the object's data in a sensible way and returns a string. Otherwise all that's printed is the name of the class which is normally not what you want. For example, a good toString() method for the Car class might be: public String toString() { return (this.licensePlate +" is moving at "+ this.speed +"km/h and has a maximum speed of "+ this.maxSpeed +"km/h." ); }
9th Apr 2019, 7:49 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 10
Rules for toString() Methods • toString() methods should return a single line of text that does not contain any carriage returns or linefeeds. • toString() methods are primarily for debugging. • toString() should not do a lot of fancy processing. toString() methods should be quick. The string returned by toString() should contain the name of the class, and names and values of the fields that represent the state of the object, unless there are an excessive number of such fields, in which case only the most important should be returned. A better Car toString() method would be: public String toString() { return "[Car: plate = "+ this.licensePlate +" speed = "+ this.speed +"; MaxSpeed = "+ this.maxSpeed +"]"; } ⟹ These rules are conventions, not requirements of the language. akshay patel https://code.sololearn.com/cmy2730Qn2tY/?ref=app
9th Apr 2019, 8:06 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 8
The secret is every object in java extends class Object and inherits its methods 😉
9th Apr 2019, 6:09 PM
D_Stark
D_Stark - avatar
+ 6
What are you unsure about? How toString() works or how come you can use this method with any object?
9th Apr 2019, 12:11 PM
D_Stark
D_Stark - avatar
+ 2
Please change your Relevant Tags to contain Java (not just 'a') it is recommended to be more specific with the question.
9th Apr 2019, 9:17 AM
Ipang
0
How can we use this method with any object
9th Apr 2019, 2:56 PM
akshay patel