1

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?

Crowley Astray
  • 172
  • 1
  • 14
  • 3
    The biggest difference is that `parseShort` returns a primitive `short`, while `valueOf` returns an instance of the wrapper class `java.lang.Short`. – Jesper Jul 28 '17 at 07:15
  • 2
    One returns a primitive `short`, the other returns a boxed `Short` – 4castle Jul 28 '17 at 07:15
  • Also, unless you have a good reason not to, you should probably be using `int`/`Integer` instead. – 4castle Jul 28 '17 at 07:21
  • Thanks for all the answers (and sorry for not seeing the Duplicate). @4castle I am using short because I want to force my coworkers to use appropiate values (they are read from a config, therefore the String conversion) – Crowley Astray Jul 28 '17 at 07:27
  • @CrowleyAstray I'll trust that you know what constitutes appropriate values. You might be interested in this question: [Why are so many of the numbers I see signed when they shouldn't be?](https://softwareengineering.stackexchange.com/q/352896/226788). The answers discuss why `int` is often the best choice. – 4castle Jul 28 '17 at 13:12

1 Answers1

1

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));
}
Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93