Search code examples
javashort

Java difference between Short.parseShort and Short.valueOf


I have recently stumbled upon another question on Stack Overflow where one person suggests using Short.parseShort(String s) and another Short.valueOf(String s).

I have tried both myself, and I found no difference in functionality and the official Documentation didn't really help me either:

Short.parseShort: Parses the string argument as a signed decimal short. The characters in the string must all be decimal digits, 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, exactly as if the argument and the radix 10 were given as arguments to the parseShort(java.lang.String, int) method.

Short.valueOf: Returns a Short object holding the value given by the specified String. The argument is interpreted as representing a signed decimal short, exactly as if the argument were given to the parseShort(java.lang.String) method. The result is a Short object that represents the short value specified by the string.

Both accept the additional Parameter radix, and both throw a NumberFormatException.

They seem to be identical, but if that is the case, why do both exist?


Solution

  • valueOf is using parseShort internally and additionally wraps the value in a boxed type Short:

    public static Short valueOf(String s, int radix)
        throws NumberFormatException {
        return valueOf(parseShort(s, radix));
    }