Skip to content

Java convert String to short example

This example shows how to convert string to short in Java using the parseShort method of the Short wrapper class including out-of-range values.

How to convert string to short in Java?

To convert a string to short value, use the parseShort method of the Short wrapper class.

This method returns a short primitive value by parsing the input string value.

Output

Important Note:

All the characters in the string must be digits, except for the first character of the string which can be a “-“(minus sign) to indicate a negative number value.

If any of the characters in the string (except for the first character if it is a minus sign) is a non-digit character, the NumberFormatException exception is thrown.

Output

Here are some of the example string values and their possible conversion to short value output.

Please note that “+” (plus sign) is allowed as the first character of the string in newer versions of Java. In the older versions, if a string has a plus sign as the first character, the parseShort method throws NumberFormatException.

Java short data type range

The short data type in Java is a 16 bit signed integer value. The range of the short variable in Java is -32768 to 32767 (both inclusive). So a short variable can have a minimum value of -32768 while the maximum value it can hold is 32767.

What happens when the string contains a number that is not in the range of the short?

When a string object contains a number that is not in the range of the short data type, and we try to convert, the parseShort throws NumberFormatException with a message saying that value is out of range as given below.

Output

This example is a part of the Java Basic Examples and Java Type conversion Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.