-1

Possible Duplicate:
Why int i = 2147483647 + 1; is ok, but byte b = 127 + 1; is not compilable?

Im a beginner with java so please appreciate this beginner question. But why is my compiler not fine with byte b = 127 + 1; but compiles fine with int i = 2147483647 + 1;

Community
  • 1
  • 1
john
  • 36
  • 2
  • 4
    Is this a joke or just a huuge coincidence? – Konrad Rudolph Jul 31 '11 at 15:05
  • Konrad, it is likely a question being asked to a student sized class of people, where those people then independently ask stackoverflow. My guess is that some professor mentioned StackOverflow as a resource in their learning program, or it's just common word of mouth information due to a club / clique / etc. All of the duplicate posters do so in mere minutes to hours of each other, and none of them have much reputation. – Edwin Buck Jul 31 '11 at 15:10

2 Answers2

2

Your compiler complains because it sees two ints being added together (int 127) and (int 1) and then it worries that some precision will be lost as it attempts to store the result (int 128) into a byte.

The numbers you selected tend to hint that you think it is related to overflow. It is not, as even if it is important to keep overflow in mind when programming, the compiler never complains about overflow issues.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
1

because when the compiler sees 127 it treats it as an int, not a byte. You need a cast to fit the result back into a byte.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276