It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes char c = (int) 1; Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "char c = (int) 1;" Watch "char c = (int) 1;" New topic

char c = (int) 1;

Michael Wiezik
Ranch Hand

Joined: Mar 19, 2004
Posts: 70

char c = (int) 1;

doesn't result with compilation error? As I tried few combinations, compilator accepts any values from char range, even if they are int-casted. Can somebody give me formal explanation? Thnx

SCJP 1.4 - 88%
SCBCD 5.0 - 90%
SCEA - 81%
Deb Sadhukhan
Ranch Hand

Joined: Nov 05, 2003
Posts: 67
Even if you don't cast 1 to int still it's int.

Compiler accepts it because at the compilation time it knows that the value can fit in char variable.

_ __ _ __ _ __ _<br />SCJP 1.4 (95%) | SCWCD 1.4 (79%)<br />Artificial intelligence is no match for natural stupidity.
Sania Marsh
Ranch Hand

Joined: Jul 12, 2004
Posts: 469
char is an "unsigned short under the roof", it will accept any unsigned short:

Hey in russian compiler is also compilator, what language do you speak?
Brian Percival
Ranch Hand

Joined: Jun 23, 2004
Posts: 163
Greetings from Hogwarts,

Bro, I got what you are asking.. but still it makes sense for the compiler not to complain...

we know that:

"char var can be assigned an int without any cast as long as it is within the char range."

so when you say char c=(int)1, you are really not saying anything different. It is totally the same as saying char c=1, becoz 1 without any cast is an int anyway.

So the compiler won't complain..since your casting is not making any difference... I think I make sense...
Michael Wiezik
Ranch Hand

Joined: Mar 19, 2004
Posts: 70
I speak both polish and russian . They are indeed similar. f.e., "kurit' travku" sounds similar to "palic trawe". On the other hand, "tusovka" has nothing common with "impreza". I like Russian and if java would not exist, I would be probably a filologist.
Thanks everyone for brief explanation. I'm taking exam in 5 days - after 2 weeks learning (no time). Wish me luck!
I agree. Here's the link:
subject: char c = (int) 1;
It's not a secret anymore!