I know that toString
is called in Java
whenever we print an object, and that is by default defined in Object
class which is superclass of all classes.
But, my teachers says that toString
is also called when we print some primitive type
(int, char
etc).
Is that true ?
If there is no implementation for toString() found in the class, then the Object class (which is a superclass) invokes toString() automatically. Hence, the Object. toString() gets called automatically.
Definitely, String is not a primitive data type. It is a derived data type. Derived data types are also called reference types because they refer to an object.
Your toString() method is actually being called by the println method.
For converting a primitive type value to a string in Java, use the valueOf() method.
Yes, but not in the sense that you would expect it to be.
System.out.println(someInt)
is just a wrapper for print
that also adds a line.
System.out.print(someInt)
calls
String.valueOf(someInt)
which in turn calls
Integer.toString(someInt)
which is a static method in the Integer class that returns a String
object representing the specified integer. This method is not the same as Integer#toString()
, an instance method that transforms its Integer object into a string representing its int value.
someInt.toString()
won't work as someInt
does not extend Object
due to its not being an 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