*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting 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 "casting" Watch "casting" New topic
Author

casting

sonali rao
Ranch Hand

Joined: Nov 03, 2003
Posts: 64
Consider the following.
char c='a';
char d=c+1; //line 1.
char e=4+4; //line 2.
I know line 1 gives error as it requires explicit casting.
I do not understand why line 2 does not give an error. 4+4 results in 8 which is of type int. why does it not require an explicit casting?
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
4 is an int literal and also a compile time constant. When you add two constants to each other, the result is a constant as well. In this case, if the resulting int const fits into char, the compiler allows such an assignment.
Harwinder Bhatia
Ranch Hand

Joined: Oct 17, 2003
Posts: 150
Sonali
Btw, if you declare c as final, line 1 would compile fine too.
Cheers
Harwinder
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
Originally posted by Harwinder Bhatia:
Sonali
Btw, if you declare c as final, line 1 would compile fine too.
Cheers
Harwinder

The same rule applies: if the compiler figures out the assignment as a result of operations on compile time constants fitting the size to the left, it'll allow it.
 
wood burning stoves
 
subject: casting
 
Similar Threads
Operator assigment question
Doubt on cast
Typecasting between char and byte
strange thing about char.
Cast byte to char