1

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 ?

maxjackie
  • 22,386
  • 6
  • 29
  • 37
  • 2
    possible duplicate of [why byte += 1 compile but byte = byte + 1 not?](http://stackoverflow.com/questions/4969339/why-byte-1-compile-but-byte-byte-1-not) – axtavt Apr 25 '12 at 07:36
  • It's only a near duplicate of this question. The other question is "what in the Java language definition causes this behavior?", whereas this question is "what is the reason for this behavior", asking for the motivation of the language definition. – Martin v. Löwis Apr 25 '12 at 07:42

2 Answers2

2

You have to write your original code as

b = (byte)(b + 10);

The problem is that b + 10 is 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.

Martin v. Löwis
  • 124,830
  • 17
  • 198
  • 235
1

Well it says possible loss of precision because compiler thinks that may be after adding 10 to b it may go over limit of byte size, but as you use b++ or b+=10 its not just adding 10 but also typcasting it automatically so as to confirm at compiler level that the value of b does not go beyond limits of byte size.

Asif
  • 4,980
  • 8
  • 38
  • 53