Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why plus operator in Java always produces Integer? [duplicate]

I have code like this

short a = 1;
short b = 2 ;
short c = a + b; // dosen't compile

What is the reason for compilation failure? x + x always produces Integer or bigger Number, but why?

like image 905
MariuszS Avatar asked Dec 01 '22 02:12

MariuszS


1 Answers

None of the binary operators will produce an Integer. However, it will use an int instead of shorter types, byte, short and char If the compiler can inline the value it can cast the value for your. e.g.

final short a = 1;
final short b = 2;
short c = a + b; // does compile, because of constant inlining.

The only operator which produces an Integer is a cast.

Integer i = (Integer) 1;

BTW: On oddity is that Java defines the 32-bit float as being "wider" than the 64-bit long value. This has the downside that float has much less precision. Consider this.

long l = 7777777777777777777L;
l += 0.0f;
System.out.println(l);

prints

7777777579364188160

Even though 0.0F was added to l it was implicitly cast to float (as float is wider) and then cast back (as an operator assignment was used) resulting in a error of ~20 billion.

like image 137
Peter Lawrey Avatar answered Mar 17 '23 03:03

Peter Lawrey