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 ?
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)
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.
Lets see how System.out.print(int)
works. According to System
API System.out
is a PrintStream
:
public static final PrintStream out
In PrintStream
src we can see how it prints ints:
public void print(int i) {
write(String.valueOf(i));
}
And this is String.valueOf(int)
from String
src:
public static String valueOf(int i) {
return Integer.toString(i);
}
If you consider following code
System.out.println(5);
Following thing will happen
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
function from PrintStream
class will be called which internally will call print(x)
function as follows-
public void print(int i) {
write(String.valueOf(i));
}
and now if you see valueOf() function in String class
public static String valueOf(int i) {
return Integer.toString(i);
}
and
Integer.toString(i)
is what your teacher meant by calling toString() method.
The primitives are autoboxed to their respective object type. So toString()
will call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.