Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Primitive types  RSS feed

 
mads svantesson
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • 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);
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!