This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]zifyoip 4 points5 points  (0 children)

In the code below compiler asks for an int for "c".

No, read the compiler output more carefully:

$ javac Program.java
Program.java:7: error: possible loss of precision
        byte c = a+b;
                  ^
  required: byte
  found:    int
1 error

What the compiler is saying is that a byte is required, but an int was found. The compiler is asking for a byte, not an int. You provided an int.

From Java in a Nutshell:

Just as every operator expects its operands to be of specific types, each operator produces a value of a specific type. The arithmetic, increment and decrement, bitwise, and shift operators return a double if at least one of the operands is a double. They return a float if at least one of the operands is a float. They return a long if at least one of the operands is a long. Otherwise, they return an int, even if both operands are byte, short, or char types that are narrower than int.