I don't follow all the rules for casting of primitives. For example, can someone clarify why I generate a compiler error when trying to cast an int to a string? class casting { public static void main(String[] s) { int x=24; byte b=8; String str = "";
str = (String)x; str = (String)b; } }
Ron Newman
Ranch Hand
Joined: Jun 06, 2002
Posts: 1056
posted
0
A String is an object. You can never cast a primitive to an object, or vice versa.
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Falshon Hauxe
Greenhorn
Joined: Aug 06, 2002
Posts: 6
posted
0
I see, so I should first make a wrapper class for the int and then try to cast it, right?
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
Take a look at the API documentation for the String class. You will find that no casting will be necessary. Here -Barry
Thanks. I used the wrapper class and then the toString() method to achieve the result. class casting { public static void main(String[] s) { int x=24; byte b=8; String str = ""; Integer wrapX = new Integer(x); Byte wrapB = new Byte(b);
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus