Java Basic Examples

Java convert String to short example

This example shows how to convert String to short in Java. This example also shows how to convert String to short primitive using Short wrapper class.

How to convert String to short in Java?

To convert String to short, use parseShort method of Java Short wrapper class.

This method returns 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 the negative short value.

If any of the character in the String (except for the first character if it is minus sign) is a non-digit character, NumberFormatException is thrown while converting String to short value.

Output

Here are some of the example String values and their possible short output.

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

Java short data type range

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

What happens when the String contains a number not in range of the short?

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

Output

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *