Java - Explicit Conversion from Int to Short
Asked Answered
L

3

15

Can someone please explain why this following statement:

short value = (short) 100000000;
System.out.println(value);

Gives me:

-7936

Knowing that the maximum value of a short in Java is 32767 correct?

Liselisetta answered 17/9, 2013 at 22:18 Comment(2)
i get -7936 when i run the same codeMicra
Sorry, it's supposed to be 1000000Liselisetta
A
25

With your value of 100 million, I get -7936. I can only get 16960 if I change 100 million to 1 million.

The reason is that short values are limited to -32768 to +32767, and Java only keeps the least significant 16 bits when casting to a short (a narrowing primitive conversion, JLS 5.1.3). Effectively this operation: 1 million mod 2^16 (16 bits in a short) is 16960.

Amaryllidaceous answered 17/9, 2013 at 22:23 Comment(0)
G
3

The way you did it merely reinterprets a smaller number of bits at the same memory location. It does not change them.

You probably want to use the max and min functions to detect when the value lies beyond of short and assign the max or min value of the short when that happens.

int n = 1000000;
short value = n > Short.MAX_VALUE ? Short.MAX_VALUE : n < Short.MIN_VALUE ? Short.MIN_VALUE : (short)n;

Update: more compactly:

import static java.lang.Math.max;
import static java.lang.Math.min;

// ...

value = (short)min(max(value, Short.MIN_VALUE), Short.MAX_VALUE);
System.out.println(value);
Gault answered 17/9, 2013 at 22:23 Comment(3)
@AppXene "it merely reinterprets a smaller number of bits starting from the same memory location"Gault
Please delete this it does not answer the question - you'll get your rep backMikol
@Mikol looks like i got my rep back, and then some more :DGault
R
3

Here's good article explaining narrowing and widening primitive conversions in Java.

short s = 696; // 0000 0010 1011 1000
byte x = (byte)s;
System.out.println("byte x = " + x);

Produces:

byte x = -72

Now you should understand why - because when we narrow short down to the byte the JVM discards the most significant part (00000010) and the result (in binary form) is 10111000. This is the same number we were looking at before. And, as you can see, it is negative, unlike the original value.

Rate answered 15/2, 2017 at 0:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.