maxjackie
maxjackie

Reputation: 23322

datatype byte in java not allowing to add any literal

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 ?

Upvotes: 1

Views: 637

Answers (2)

Martin v. Löwis
Martin v. Löwis

Reputation: 127587

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.

Upvotes: 2

Asif
Asif

Reputation: 5038

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.

Upvotes: 1

Related Questions