+ 2

Java Question Why this code give me a error?

byte a = 10; byte b = 15; byte c = a + b; System.out.print (c); I dont know why...

27th Jun 2017, 11:47 PM
Kabuto Yaqushi
Kabuto Yaqushi - avatar
3 Antworten
+ 5
Both a and b are byte type(1byte) variable which is smaller than int type (4byte) So + operator convert a and b to int type before calculation. Therefore the result of a + b will be int type. You assign int type value(a + b) to byte type variable(c) without casting. So it makes error...
27th Jun 2017, 11:54 PM
김정제(Legacy)
김정제(Legacy) - avatar
+ 5
Maybe you should do like byte c = (byte)(a + b); or int c = a + b;
27th Jun 2017, 11:49 PM
김정제(Legacy)
김정제(Legacy) - avatar
+ 2
@ Legacy Thanks I think u r right..
28th Jun 2017, 12:32 AM
Kabuto Yaqushi
Kabuto Yaqushi - avatar