Subscribe to the RSS feed for the devdaily.com blog
Page not found (404 error) | alvinalexander.com

Page not found (404 error)

I’m sorry, the URL you are looking for can't be found.

This may be because I’ve made several significant changes to the website lately. If you want to take a few moments to search for the document you were looking for, you can try the Search Page here.

(I am trying to fix all the links I have broken, but it takes time.)

Thank you for your patience, and have a nice day!

Alvin Alexander
Owner, Editor, Link-breaker, Repairman,
AlvinAlexander.com


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