Click here to Skip to main content
14,983,344 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I mean

Short a=10;
Short b=10;
Short c=a+b;
In this case I got compilation error but in below code

Int a=10;
Int b=10;
Int c=a+b;
I didn't get any error any one can explain in detail I have confused so long

What I have tried:

I have Read in Google as if we add two short variables you will get int type
But why it is not possible in adding two int variables converted into double or long variable types
Posted
Updated 13-Mar-18 6:13am

1 solution

It looks to be an oddity in the Java Language Specification:

"If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion."

Which I take to mean:

short + byte = int
short + short = int
int + short = int
int + int = int
int + long = long
long + long = long

I find that a bit inconsistent, to be honest, but that is the way that it's defined.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900