+ 2
Can somebody explain please, why this code gives an error, and what should one do to fix it, except to use int...
class MyClass { public static void main(String[ ] args) { byte a = 2; byte b = 1; byte c = a + b; System.out.print(c); } }
4 odpowiedzi
+ 3
When you add/subtract 2 or more byte types together they are implicitly converted to int to ensure that the result can be held. For instance, if you add 2 bytes together and the result is beyond the upper bounds of the byte types range the result would not be what you expect, but a byte overflow and would wrap around to the lower bounds plus the remainder. You should first ensure the result doesn't extend beyond the bounds and then convert the result back into a byte via a cast.
byte range is -128 to 127
(byte)(a + b)
class MyClass {
public static void main(String[ ] args) {
byte a = 2;
byte b = 1;
byte c = 0;
if((a + b) <= 127) {
c = (byte)(a + b);
}
// perform any other checks you may need as well
System.out.print(c);
}
}
+ 3
thanks a lot for your explanation.
So math. operations directly with byte-type variables are not allowed in java right?
is it a good practice to use an int instead of byte and not thinking about possible errors, in math. operations?
+ 2
the compiler is refusing to downcast without explicitly being told so.
+ is returning an integer and c is byte. So you can pick from two options. Either downcast by hand or call c an integer.
I wrote a code with comment to show you this. I don't know to link to it here on the phone.
+ 1
I would say: Go only for bytes if you are definitely sure that your Number is in that range ChaoticDawg pointed out.
Otherwise go for int since it's the standard numeric basic type in Java (at least as far as I know)