i am trying some java code like this
class Test {
public static void main (String [] args){
byte b = 10;
b = b + 10;
}
}
after saving when i tried to compile it , it is giving me an error
D:\java\Test.java:4: possible loss of precision
found : int
required: byte
b = b + 10;
^
1 error
but there is no if try something like this
b++;
b+=10;
it is perfectly alright
what is reason for this ?
You have to write your original code as
The problem is that
b + 10is of type int, as the byte is widened to an int.The reason for this is that there is a conceptual ambiguity, if b was, say, 120. Is then b+10 equal to 130, or is it equal to -126?
Java designers decided that addition should be carried out in int in this case, so that 120+10 is 130. Then it can’t be stored into a byte.
For
b+=10, it’s clear that you want to modify b, so it’s a byte addition.