Why am I not getting the output since byte
value is from -128 to 127 and the result is 30 ?
class test15 {
public static void main(String ...s) {
byte a = 10;
byte b = 20;
byte c = a+b;
System.out.println(c);
}
}
CompileTime vs RunTime
a,b are bytes and bytes doesn't have addition operator. At run time, since a,b are not final and integer addition takes place which result is an int
. And you are trying to assign it to a byte. Which results a compilation error.
byte c = (byte)a+b;
And as a side note. try to change your code as
final byte a = 10;
final byte b = 20;
byte c = a + b;
That compiles fine because of narrowing conversion and it is possible, if all the operands are constant values in an expression.
You must cast to byte
. Since a
and b
are of type byte, Java will convert them to an int
, and then the result is an int
.
byte c = (byte) (a+b);
Compile time error, if I change this
byte c = a + b;
to
byte c = (byte) (a + b);
I get the output
30
Change
byte c = a + b;
to
byte c = (byte)(a + b);
It works for me.
Java converts the result of arithmetic operations to int
type by default. Try this:
public static void main(String... s)
{
byte a = 10;
byte b = 20;
byte c = (byte) (a + b);
System.out.println(c);
}
That (byte)
changes the int value returned by (a+b) into a byte value. Normally, this cannot be done, as the range of int is much greater than the range of byte, so a loss of precision would occur. Using casting forces the conversion, regardless of precision.
There is no instruction set to perform operation on a byte
type. Rather the instruction set for int
type is used for the operation on boolean
, byte
, char
, and short
types. http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11.1
Also A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting; a casting operation to be performed by the programmer
The result will be an Integer. For this you must do
byte a = 10;
byte b = 20;
byte c = (byte) (a + b); //u will have to typecast int to byte
System.out.println(c);
Here's whats happening
byte a = 10;
variable a of byte type created 10 assigned to it.
byte b = 20;
variable b of byte type created 10 assigned to it.
byte c = a+b;
a+b
is automatically promoted to integer, since now result of summation is integer you cannot assign integer to byte.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.