Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is toString called for primitive types also?

Tags:

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 ?

like image 231
Gagan93 Avatar asked Sep 06 '13 10:09

Gagan93


People also ask

Is toString automatically called?

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.

Is a string a primitive type?

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.

How is toString called?

Your toString() method is actually being called by the println method.

Which method converts primitive type into string?

For converting a primitive type value to a string in Java, use the valueOf() method.


1 Answers

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.

like image 64
nanofarad Avatar answered Sep 23 '22 04:09

nanofarad