Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting an int to a char

 
Kelly Harris
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There does not seem to be an easy way to take an int (like a 32) and return its character representative ( a Space). I looked through the Integer and Character classes along with some other help topics. This seems so simple but I cannot find the answer.
Thanks
Kelly Harris
 
Jason Kretzer
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have no idea if this will work but...
Integer i = new Integer(32);
char c = (char)i;
This code is only proved correct, I have not tested it.

HTH,
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kelly,
In what context are you speaking? There are various I/O methods that use ints instead of chars. Why can't you just typecast the int to a char? :

Hope this helps
Michael Morris
SCJP2
 
Kelly Harris
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I feel real stupid now. I was trying to type cast it into a String rather than just a char. I was thinking too hard (smell the smoke).
 
Karl Laird
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just reiterating that the method mentioned in the second post will not work as you are trying to cast an object (Integer) into a simple type (char). This should throw a compile time exception. The method mentioned in the third post is correct - directtly cast from simple type (int) to simple type (char).

Of course if you really want it to be a string you could always use
String myString = myInt + "";
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One thing to note about casting chars and other primitives. The following code is legal because a char (2 bytes) is smaller than an int (4 bytes), therefore a windening conversion is taking place and an implicit cast is done.

However, the following code is illegal, even though both data types are 2 bytes.

The reason this is illegal is because the data type char, unlike other primitive types (boolean and void excluded), is unsigned. Therefore, the range of a char does not exactly match the range of a short (and vice versa).
Just something to keep in mind.
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic