I am trying to add two values in a byte array. This is my code:
byte[] ars = {3,6,9,2,4};
ars[0] = (byte)ars[0] + (byte)ars[4];
System.out.println( ars[0] );
I get this error on compilation:
Main.java:9: possible loss of precision
found : int
required: byte
ars[0] = (byte)ars[0] + (byte)ars[4];
^
1 error
Any help is, as always, much appreciated.
In Java, the sum of two byte
s is an int
. This is because, for instance, two numbers under 127 can add to a number over 127, and by default Java uses int
s for almost all numbers.
To satisfy the compiler, replace the line in question with this:
ars[0] = (byte)(ars[0] + ars[4]);
I cam across this question a while back, and collected all the findings here : http://downwithjava.wordpress.com/2012/11/01/explanation-to-teaser-2/
We all know bytes get converted to ints during an arithmetic operation. But why does this happen? Because JVM has no arithmetic instructions defined for bytes. byte type variables have to be added by first 'numerically promoting' them to 'int' type, and then adding. Why are there no arithmetic instructions for the byte type in JVM? The JVM spec clearly says:
The Java virtual machine provides the most direct support for data of type int. This is partly in anticipation of efficient implementations of the Java virtual machine's operand stacks and local variable arrays. It is also motivated by the frequency of int data in typical programs. Other integral types have less direct support. There are no byte, char, or short versions of the store, load, or add instructions, for instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With