Learn Java: Java Q&A: How do I convert a String to a short?
Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


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.

 


Read the BLOG

Copyright © 1998-2002 DevDaily Interactive, Inc.
All Rights Reserved.