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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With