Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Explicit Conversion from Int to Short

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?

like image 252
Octocat Avatar asked Sep 17 '13 22:09

Octocat


People also ask

How do you convert to short in Java?

Use valueOf() method to convert a String in Java to Short. Let us take a string. String myStr = "5"; Now take Short object and use the valueOf() method.

Which of the following can convert an integer number to a short integer?

shortValue() is an inbuilt method of java. lang which returns the value of this Integer in the short type . Parameters: The method does not take any parameters. Return Value: The method returns the integer value represented by this object after converting it to type short.


1 Answers

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.

like image 191
rgettman Avatar answered Oct 03 '22 03:10

rgettman