wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Question re casting from Random.nextInt to char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question re casting from Random.nextInt to char" Watch "Question re casting from Random.nextInt to char" New topic
Author

Question re casting from Random.nextInt to char

richard rehl
Ranch Hand

Joined: May 21, 2007
Posts: 36
I find this curious - to generate a random character, it seems like you have to first assign the output of the Random.nextInt() method to an int (or double or whatever) and THEN cast that to a char. I'm wondering why you can't just cast the output of the Random.nextInt() method directly to a char? For example:

will work to give you the lowercase characters randomly, but gives me a compiler error:
Type mismatch: cannot convert from int to char

Can anyone enlighten me?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

richard rehl wrote:
When I do that I'm getting a different error: Possible loss of precision

But that is easy to solve just add parentheses


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
richard rehl
Ranch Hand

Joined: May 21, 2007
Posts: 36
Yeah, I had thought about adding parentheses but hadn't gotten around to it. That does make the compiler happy.

I'm still wondering why the compiler doesn't like
I guess I assumed that the cast applied to the entire right side of the assignment; and I also thought that any int-sized or smaller expression results in an int. So if the result of rand.nextInt() is an int, and you add a char to it, you'll get an int, which you then can cast to a char.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19799
    
  20

The result of any mathematical operator is always at least an int; never byte, short or char. So even though (char)rand.nextInt(26) is a char, and 'a' is a char, the result of adding them is an int. You'll need to add first, then cast:
Side note: combining operators with assignment (e.g. +=) already has this cast in it. So the following is also allowed:
The previous is clearer though; after all, what is the char value of 25, for instance? I don't know without looking it up, whereas 25 + 'a' is clearly 'z'.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
jQuery in Action, 2nd edition
 
subject: Question re casting from Random.nextInt to char