21

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 ?

4

4 回答 4

50

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.

于 2013-09-06T10:01:49.167 回答
24

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);
}
于 2013-09-06T10:17:12.590 回答
1

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.

于 2013-09-06T10:17:35.980 回答
0

The primitives are autoboxed to their respective object type. So toString() will call.

于 2013-09-06T10:03:43.870 回答