This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Adding short values" Watch "Adding short values" New topic
Author

Adding short values

Mehul Sanghvi
Ranch Hand

Joined: Feb 04, 2002
Posts: 134
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.
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:
here
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
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

Joined: Sep 16, 2005
Posts: 1780
My New Year's resolution is to be less terse
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Adding short values
 
Similar Threads
Confused help
pass by value
data type short
wrapper
Assignments