Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(string) and .toString and other typecasting why is it needed?

Tags:

java

may i know why is there .toString() when you can use (String) instead? and vice versa and also for numbers can use the wrapper class's so why do we need to have a (double)? etc

like image 581
sutoL Avatar asked Nov 26 '25 16:11

sutoL


2 Answers

Because they are different things.

Integer i = Integer.valueOf("0");
String zero1 = i.toString(); // WORKS
String zero2 = (String) i; // FAILS

The toString() method is a method of each object to obtain a string representation of the object.

Casting is used when you know what the type of the object is, but it is currently referred as a supertype.

like image 180
Bozho Avatar answered Nov 29 '25 04:11

Bozho


(String) is a class cast, which works only if the object is actually of the type you are casting to (including subclasses - however, String is final, so in this case there can be no subclasses). And if the type of the object is something else than expected, it fails with a ClassCastException. A cast does not create a new object, neither does it change the original, only gives you a different type of reference to it.

OTOH, toString() is a (potential) conversion which is defined for all objects, thus always yields results (except when invoked on a null pointer of course). I wrote potential, because for Strings obviously no conversion is taking place. In other cases, a conversion in general usually creates a new object (in our case, a String), and might even modify the internal state of the original object (e.g. in case it is caching the result of the conversion - although this difference should not be visible to the outside world).

like image 30
Péter Török Avatar answered Nov 29 '25 06:11

Péter Török



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!