File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Casting rules Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting rules" Watch "Casting rules" New topic
Author

Casting rules

Falshon Hauxe
Greenhorn

Joined: Aug 06, 2002
Posts: 6
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
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
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
Take a look at the API documentation for the String class. You will find that no casting will be necessary. Here
-Barry


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Falshon Hauxe
Greenhorn

Joined: Aug 06, 2002
Posts: 6
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);

str = wrapX.toString();
str = wrapB.toString(); //overwrite str

System.out.println(str);

}
}
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Did you not consider:
?
-Barry
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Of course you can always try this:
int x = 10;
String s = "" + x;


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Falshon Hauxe
Greenhorn

Joined: Aug 06, 2002
Posts: 6
ahhh, thanks.
Those are a litte more elegant, eh.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Yes, but Thomas always does the advanced stuff
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
See also http://jinx.swiki.net/77


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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting rules