Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting rules

 
Falshon Hauxe
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A String is an object.
You can never cast a primitive to an object, or vice versa.
 
Falshon Hauxe
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see, so I should first make a wrapper class for the int and then try to cast it, right?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the API documentation for the String class. You will find that no casting will be necessary. Here
-Barry
 
Falshon Hauxe
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you not consider:
?
-Barry
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course you can always try this:
int x = 10;
String s = "" + x;
 
Falshon Hauxe
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ahhh, thanks.
Those are a litte more elegant, eh.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but Thomas always does the advanced stuff
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See also http://jinx.swiki.net/77
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic