programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Bear Bibeault
• Ron McLeod
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Tim Cooke
• Liutauras Vilda
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• fred rosenberger
• salvin francis
Bartenders:
• Piet Souris
• Frits Walraven
• Carey Brown

# numeric promotional rules

Ranch Hand
Posts: 48
I need some clarification about numeric promotional rules. example as below :

can someone explain me why line 3 is not compiled. I think there is nothing wrong with it as I casted data types to short. Why i need to put x*y inside parenthesis?

Thanks

Enthuware Software Support
Posts: 4450
41
Cast operator has higher precedence than * . So  (short) x*y; is same as ( (short) x)*y);
The result of any integral variable multiplied by another integral variable will at least be an int, which you cannot assign to a short without a cast. You will thus need to cast the result to a short -  (short) ((short) x*y); Or simply, (short)(x*y);

The rules of numeric promotion are given here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.6.2

Ranch Hand
Posts: 312
6
Precedence

short z = short * int ;
short z = int * int;
short z = int; //does not compile

Claire Chan
Ranch Hand
Posts: 48
yes but I wonder why we need to put x*y inside parenthesis like (x*y). For eg,

int x = 1

short y = (short) x; // we don't need to put x inside parenthesis like previous example.

Charles O'Leary
Ranch Hand
Posts: 312
6
numeric promotion deals with two values, right?  "short(x)": x is the only value.

Claire Chan
Ranch Hand
Posts: 48
that really clarifies my doubt for putting parenthesis for two values. Thanks Charles

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.