Byte arithmetic: How to subtract to a byte variable?
Solution 1
Do like this.
a = (byte)(a - 1);
When you subtract 1 from a
then its integer value. So to get assign the result in byte you need to do explicit type casting.
Solution 2
In Java math, everything is promoted to at least an int
before the computation. This is called Binary Numeric Promotion (JLS 5.6.2). So that's why the compiler found an int
. To resolve this, cast the result of the entire expression back to byte
:
a = (byte) (a - 1);
Solution 3
a = a - 1;
// here before subtraction a is promoted to int data type and result of 'a-1' becomes int which can't be stored in byte as (byte = 8bits and int = 32 bits).
Thats why you'll have to cast it to a byte as follows :
a = (byte) (a - 1);
Solution 4
Do this:
a -= 1;
You even don't need explicit cast, compiler/JVM will do it for you.
Should you change the variable type to int nobody can say, having only information you provided.
A variable type is defined by the task you are planning to perform with it.
If your variable a counts fingers on someone's hands, why would you use int? Type byte is more than enough for that.
Comments
-
mevqz almost 2 years
I'm getting an error when I'm trying to do somethink like this:
byte a = 23; a = a - 1;
The compiler gives this error: Test.java:8: possible loss of precision found : int required: byte a = a - 1; ^ 1 error
Casting doesn't solve the error... Why the compiler don't let me do it? Should I need to transform the variable 'a' into an int?