+ 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);

4th Jul 2018, 4:56 PM
Prince Raj
8 Antworten
+ 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......
4th Jul 2018, 5:30 PM
Arun Tomar
Arun Tomar - avatar
+ 10
KrOW it by mistakes happened.. thanks to tell me
4th Jul 2018, 5:33 PM
Arun Tomar
Arun Tomar - avatar
+ 6
change: byte c = a + b; to int c = a + b; OR change all to int
4th Jul 2018, 5:00 PM
Agent
Agent - avatar
+ 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
4th Jul 2018, 5:26 PM
KrOW
KrOW - avatar
+ 2
Arun Tomar It dont work because it do casting only to 'a' then you will have same situation
4th Jul 2018, 5:32 PM
KrOW
KrOW - avatar
+ 1
👍👍👍
4th Jul 2018, 5:35 PM
KrOW
KrOW - avatar
+ 1
thanks for all
4th Jul 2018, 6:26 PM
Prince Raj
+ 1
because byte can only store short data memory . if you try int it gets work.
4th Aug 2018, 9:51 AM
hemanth v.hemanth
hemanth v.hemanth - avatar