How do I convert a String to a short with Java?

Question: How do I convert a String to a short with Java?

Answer:

The Short class includes a method named parseShort() that serves just this purpose. An example of a simple program that performs this conversion is shown below:

public class s2s {

   public static void main (String[] args) {

      // String s = "fred";    // do this if you want an exception

      String s = "100";

      try {
         short sh = Short.parseShort(s.trim());
         System.out.println("short sh = " + sh);
      } catch (NumberFormatException nfe) {
         System.out.println("NumberFormatException: " + nfe.getMessage());
      }

   }

}

Other notes

  • Short.toString(short s) is used to convert in the other direction, from a short to a String.
  • If you're interested in converting a String to a Short object, use the valueOf() method of the Short class instead of the parseShort() method.

Related links

There is much more content related to Java and the String class on the blog, including these posts:


devdaily logo