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 ashortto a String.- If you're interested in converting a
Stringto aShortobject, use thevalueOf()method of theShortclass instead of theparseShort()method.
Related links
There is much more content related to Java and the String class on the blog, including these posts:
- A Java toString method that uses reflection to dynamically print class fields
- Use String.format to format a Java String
- A cheat sheet (reference page) for printf format specifiers
- How to convert a Java String to an int
- How to create an array of Strings (or any object) in Java
- A method to return the longest String in a given array of Strings
