Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

char c = (int) 1;

 
Michael Wiezik
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why

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
 
Deb Sadhukhan
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sania Marsh
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gula,
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic