• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Primitive types

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
//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

//Best regards mads
 
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic