+ 2
Why this code shows error and please explains it to me?
byte a = 5; byte b = 5; byte c = a + b; System.out.println(c);
8 Réponses
+ 8
Prince Raj💲💲
it because
integer value are treated as integer literal
for eq
5
3
7
all are integer literal..
as you know that..
=Rhs is solved first..
Integer+integer is equal to integer
5+5 is 10 is also a integer literal..
and
and you try to assign integer value
to byte..
i.e i give error..
if you want to run this code..
so
byte c=(byte)(a+b);
then it work......
+ 10
KrOW
it by mistakes happened..
thanks to tell me
+ 6
change:
byte c = a + b;
to
int c = a + b;
OR
change all to int
+ 2
Java must promote "a" and "b" to int for make addition operation and, while to this, its all ok. The problem and that after this, Java must convert an int to a byte (by assignement operator) and if you dont EXPLICITALLY tell to Java that you want this, it complain about a probable data loss... Beside Agent suggestion you can tell to Java, that you want cast int to byte explicitally:
byte c= (byte)(a+b);
Anyway note that this warning its not unuseful
+ 2
Arun Tomar It dont work because it do casting only to 'a' then you will have same situation
+ 1
👍👍👍
+ 1
thanks for all
+ 1
because byte can only store short data memory .
if you try int it gets work.