File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Convert number to character of that value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Convert number to character of that value" Watch "Convert number to character of that value" New topic

Convert number to character of that value

John Warner

Joined: Sep 03, 2006
Posts: 2
How do I convert say
int num = 65;
to a character value of "A"
that is the decimal 65 is the letter A in Ascii. I need to know how to force this conversion. I tried
char c;
c = (char)num;

the compiler refuses to do the convert. Note I do not want the digits 6 and 5, I want the letter A as output. Is this even possible with Java?

In basic you have the chr(65) function which returns the letter A. I'm looking for the same functionality. Ulitmately I want to use math.random to generate some random letters.

Thanks for help a newb.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195


Welcome to JavaRanch!

What you've shown is perfectly fine -- don't know why you couldn't get it to work. If you show an actual code example that won't compile for you, we could tell you what the problem is with it. But

int i = 65;
char c = (char) i;

will work perfectly.
[ September 03, 2006: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968

Dude...Works fine for me in eclipse.

Here's the whole class:

class CharTest {
public static void main(String args[]) {
int num = 65;
char c;
c = (char)num;

John Warner

Joined: Sep 03, 2006
Posts: 2
Fellas, thanks, I found my error. I was trying to return a String from the function that I was doing the convert in. As soon as I added a Character.toString(myChar) everything fell into place. My real problem was thinking the compiler was not going to allow this at all rather then me nit understanding what had to be done. Once you both said 'hey this works' I started looking harder at my code.

Thanks again!
I agree. Here's the link:
subject: Convert number to character of that value
It's not a secret anymore!