This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "byte" Watch "byte" New topic


Sireesha Mullapudi
Ranch Hand

Joined: Jun 26, 2006
Posts: 74
Hi,In the following code

int k=2147483647+1;
byte bt=127+1;

why int is not giving compile time error?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Because the type of the result of the addition is an int.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi Lakshmi,

in the byte case, you perform an addition.
Because of the plus, both bytes are converted to ints automatically (language specification, 5.6.2 Binary Numeric Promotion) and the result computed at compile time. The compiler recognizes that the result (128 I think, didn't check it on a calculator) is too big for a byte, so a compiler error occurs.

With the ints, everything stays an int, so the compiler does not know, that an overflow will occur. The calculation is made internally with an int, so the compiler cannot know, that it is "too big" - internally the value cannot be too big, due to overflow, it just adds up to minus 2147483648.
And that fits into the variable k.


all events occur in real time
Sireesha Mullapudi
Ranch Hand

Joined: Jun 26, 2006
Posts: 74
It is sorta covered in the JavaRanch Style Guide.
subject: byte
Similar Threads
Wrapper Class Problem
The i++ operator
Problem in execution of code
Exception errror in a program