jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes adding byte and int 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 "adding byte and int" Watch "adding byte and int" New topic
Author

adding byte and int

Laiq Ahmed
Ranch Hand

Joined: Jan 04, 2010
Posts: 44
Hi,

Can anyone explain why the following in not ok?

byte a = 12 + 14; // ok
byte b = a + 20; // not ok
byte b = (byte)(a + 20); // ok

My understanding is that I am adding byte and int and putting it (result is an int) in a byte. Compiler should implicitly typecast it which is done when I do: byte z = 11;

Cheers
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
value of byte range from -128 to 127 so 11 is not considered an int but if you go out of this range you will have to cast explicitly.
or if you had done something like this the also you need expliciti cast:


a + 20 results in an int so you need an explicit cast.


SCJP 1.6 96%
Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521
actually 12+14 is a compile time constant...so the compile puts the cast for you....but a+20 is not a compile time constant....the value of a is determined at runtime....the compile doesnt put a cast there..that is why 12+14 ran and a+20 didnt


scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown
Laiq Ahmed
Ranch Hand

Joined: Jan 04, 2010
Posts: 44
I read that whole numbers are by default treated as integer in Java. So

byte i = 2;

will mean 2 as integer is being put in a byte after implicit typecasting.

Is this right?

Cheers
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
yup, as raju said these are compile time constants and have implicit cast.
Laiq Ahmed
Ranch Hand

Joined: Jan 04, 2010
Posts: 44
Thanks guys
 
Don't get me started about those stupid light bulbs.
 
subject: adding byte and int