user6556461 user6556461 - 4 months ago 18
Java Question

Float class toString method

Why toString() method present in any type wrappers class (also subclass of Number class) is static while passing number as parameter but not when invoking on an object?

Like in Float class:-

When passing number

static String toString(float num)


When invoking on Object:-

String toString( )

Answer

They are two different methods.

public static String toString(float f)

is a static method, so is associated to the class, not to instances. You don't need an instance to call it. So a static method is called statically by for example Integer.toString(f)

public String toString()

is a instance method, so is associated to instances of the class and not to the class itself. You must have a instance to call it.

To do what you ask, the static method should have been provided in two flavors : one with the static modifier and another without the static modifier (instance method) while the one with the instance method will never use the state of its instance to do the toString(). So why we should create a instance method for that ?