java.lang.Short parseShort​(String s, int radix)

Description

The Short.parseShort​(String s, int radix) java method is used primarily in parsing a String method argument into a Short object in consideration with the radix specified. The Short object is a wrapper class for the short primitive data type of java API. Even though the conversion of String to Short object is a basic stuff, I am suggesting that you should have a mastery on it. In my years of java programming, I have encountered so many instances that I have to convert from String object to another data type. The Short.parseShort(String s, int radix) method is a very convenient Java API to transform a user input in String format into a more robust object type which in this case the Short.

This method parses the string argument as a signed short in the radix specified by the second argument. The characters in the string must all be digits, of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value) except that the first character may be an ASCII minus sign ‘-‘ (‘\u002D’) to indicate a negative value or an ASCII plus sign ‘+’ (‘\u002B’) to indicate a positive value. The resulting short value is returned.

Make a note that the parseShort method of Short class is static thus it should be accessed statically. Mean to say the we would be calling this method in this format:

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java parseShort method non statically.

Important Notes:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘\u002D’) or plus sign ‘+’ (‘\u002B’) provided that the string is longer than length 1.

Method Syntax

public static short parseShort​(String s, int radix) throws NumberFormatException

Method Argument

Data Type Parameter Description
String s a String containing the short representation to be parsed
int radix the radix to be used while parsing s

Method Returns

The parseShort​(String s, int radix) method of Short class returns the short represented by the string argument in the specified radix.

Compatibility

Requires Java 1.1 and up

Java Short parseShort​(String s, int radix)  Example

Below is a simple java example on the usage of parseShort​(String s, int radix) method of Short class.

Sample Output

Below is the sample output when you run the above example.

Java Short parseShort(String, radix) method example output