• 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
  • 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

Adding short values

 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


The above code gives a compile time error of type mismatch, cannot convert int to short.
If c is declared as int then the output is 1.
And if casting is removed the output is 32769.
Hence int the code

the value on right hand side is evaluated to 1, which is logical.

The question is: Why is that value not assigned to type short @ //1

Regards,
Mehul.
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As you say the sum of the two numbers is 32769
Since The maximum positive number a short can hold is 32767 then you can't put it into a short (only int and above).

Now let's look at what happens in each case:

int x=a+b => Here you just get 32769 like you noticed because thats the sum of the numbers.

int x=(short)a+b => here you still get 32769 but because of the cast to short we only look at the lower 15 bits which have only 1 in them, so we get 1.

For more info look into this url:
here
 
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

as Jeff writes, the code will work with the "short cast" applied to the entire addition expression.

WHY?: because the compiler will convert all types in an integer maths expression to the "int" type (if the types aren't int or long). So your "a" and "b" are temporarily copied to ints during the addtion process. You need to recast the entire expression, just like Jeff suggests.

Stuart
[ December 30, 2005: Message edited by: Stuart Goss ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My New Year's resolution is to be less terse
 
reply
    Bookmark Topic Watch Topic
  • New Topic