Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

adding byte and int

 
Laiq Ahmed
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Laiq Ahmed
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yup, as raju said these are compile time constants and have implicit cast.
 
Laiq Ahmed
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic