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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Primitive types

Greenhorn
Posts: 1
• Number of slices to send:
Optional 'thank-you' note:
//how can it be that I can't add 2 short together as a short

short a = 2;
short b = 4;
short c = 0;
int d ;

//why don't this works c = a + b ;
//why don't this works c = (short)a + (short)b;
//why don't this works c = (int)a + (int)b;
//why does this works d = a + b ;

long k = 12;
double e = 4 ;
float h ;
h = (float)e + k;

//here I use a explicit cast on the double and its works fine
//, how come I can't cast the short

Ranch Hand
Posts: 226
• Number of slices to send:
Optional 'thank-you' note:
See the java language specification, �5.6.2:

if either operand is a double,
the other operand is converted to double
otherwise, if one of the operands is a float,
the other operand is converted to a float
otherwise, if one of the operands is a long,
the other operand is converted to a long
otherwise,
both operands are converted to int

you would need to cast to short after the addition as in
c = (short) (a + b);

Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by Timmy Marks:
... you would need to cast to short after the addition...

Exactly. And understand that you could lose information by doing so, which is why the explicit cast is required.

 Don't get me started about those stupid light bulbs.