wood burning stoves 2.0
The moose likes Beginning Java and the fly likes Adding short values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Adding short values" Watch "Adding short values" New topic

Adding short values

Mehul Sanghvi
Ranch Hand

Joined: Feb 04, 2002
Posts: 134

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

Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
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:
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780

There is no emoticon for what I am feeling!
Stuart Goss
Ranch Hand

Joined: Mar 21, 2001
Posts: 169

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.

[ December 30, 2005: Message edited by: Stuart Goss ]
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
My New Year's resolution is to be less terse
I agree. Here's the link: http://aspose.com/file-tools
subject: Adding short values
It's not a secret anymore!