why casting int to String is not possible through brackets method
when I try to cast int to String through this way, the compiler tells me they are inconvertible types :confused: , I know that there are other ways for holding int value as a String, but why not casting
Code :
[FONT="Courier New"]int num;
String hold;
num = 14;
hold = (String) num; // doesn't work !![/FONT]
Re: why casting int to String is not possible through brackets method
The simple answer is because Sun (now Sun/Oracle) decided not to implement this type of casting :P
Casting (either implicit or explicit) can only take place along the inheritance hierarchy. As Integers (the wrapper class for int's) don't inherit from Strings at any point along their heirarchy, they can't be casted to Strings.
Integers do inherit from Object, so you can do something like this:
Code :
int a = 5;
Object o = (Object) a; // no compile or runtime errors!
As a side note, Sun did decide to implement some pretty funny operator overloading of the + operator for Strings, which calls the toString() method on both operands and concatenates the two strings together.
Code :
Integer num = 14;
String myString = "" + num;
// same as;
String myString = "".toString().concat(num.toString());
There is also some pretty interesting handling of primitives to conform with how casting of primitives operates on C/C++ and other C-based languages.
Code :
int value = 0xFF;
byte myByte = (byte) value;
System.out.println(myByte);
This will result in the value -1 (since by taking the 8 LSB's you get the byte value 11111111, which in two's compliments notation for signed values is -1)
Re: why casting int to String is not possible through brackets method