• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Characters

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi! I have a question. Why is this allowed?
char c = 34;
Shouldn't it be:
char c = (char)34;
When I tried it out in a test program, the output for both lines of code was the same, the " character.
I think I'm missing something here. Thank you in advance.
 
Ranch Hand
Posts: 1514
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The cast was not needed because 34 is within the valid range for a character. The conversion is done automatically here. try assing a very large number to your character. The compiler will complain. ex. char c = 100000

Bosun
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Bosun.
Are these valid ways of creating and initializing char variables?
char c = 'U';
char c = 67;
char c = '\u0067';
char c = '\r';
Thanks again.
 
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also, the fact that you have assigned a literal value makes it legal without the cast. If you tried something like:
<code>
<pre>
byte b = 34;
char c = b;
</pre>
</code>
the compiler would complain, telling you an explicit cast was required.
------------------
"One good thing about music - when it hits, you feel no pain"
Bob Marley
 
Gaia Nathan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah ha...I'm clearer now. Thanks to Bosun and Michael.
Michael, nice quote.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic