This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Characters Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Characters" Watch "Characters" New topic
Author

Characters

Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
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.
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1506
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


Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
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.
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
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


"One good thing about music - when it hits, you feel no pain" <P>Bob Marley
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Ah ha...I'm clearer now. Thanks to Bosun and Michael.
Michael, nice quote.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Characters
 
Similar Threads
How to print in Double quotes ?
c+=i != c=c+i
char z =1; no single quotes OK?
about cast
assignments and + operator