Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Question re casting from Random.nextInt to char  RSS feed

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
richard rehl
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sheriff
Posts: 21421
94
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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'.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!