Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Basic Operator Return Type [duplicate]

Tags:

java

Is Java Operators return int type?

short a = 1;
short b = 2;

short c = a&b;
short d = a+b;
long e = a&b;

in case of 'c', 'd' they have type mismatch error. why? and case of 'e' no error. why??

like image 815
Super Shark Avatar asked May 31 '26 09:05

Super Shark


1 Answers

Any operation between two variables of integer type that are smaller than int results in an int. So:

short + short -> int
short + byte -> int

etc. It's mentioned in the Java Language Specification.

Therefore you have to cast the result of a + b to short in order to assign it back to a variable of type short. Please note, that you may lose data if you do so.

However long is bigger than int. The assigment ist valid.

like image 143
Marcinek Avatar answered Jun 01 '26 23:06

Marcinek