Java Convert String To Short Example

In this article, we will show you how to convert Java String to wrapper Short class or primitive type short code examples. There are different ways we can convert Java String to wrapper Short class or primitive type short.
In this post, we will demonstrate converting String to wrapper Short class or primitive type short in 4 ways.
Java Convert String To Short Example

Java Convert String To Short Example

  1. Convert using Short.parseShort()
  2. Convert using Short.valueOf()
  3. Convert using new Short(String).shortValue()
  4. Convert using DecimalFormat
Refer the comments in below program are self-descriptive.
import java.text.DecimalFormat;
import java.text.ParseException;

/**
 * ConvertStringToShortExamples
 * @author javaguides.net
 *
 */
public class ConvertStringToShortExamples {
 public static void main(String[] args) {
  // Convert using Short.parseShort
  String numberAsString = "100";
  short number = Short.parseShort(numberAsString);
  System.out.println("Convert using Short.parseShort() : " + number);

  // Convert using Byte.valueOf()
  short number1 = Short.valueOf(numberAsString);
  System.out.println("Convert using Short.valueOf() : " + number1);

  // Convert using new Short(String).intValue()
  short number2 = new Short(numberAsString).shortValue();
  System.out.println("Convert using new Short(String).intValue() : " + number2);

  // Convert using DecimalFormat
  DecimalFormat decimalFormat = new DecimalFormat("#");
  try {
   short number3 = decimalFormat.parse(numberAsString).byteValue();
   System.out.println("Convert using DecimalFormat : " + number3);
  } catch (ParseException e) {
   System.out.println(numberAsString + " is not a valid number.");
  }
 }
}
Output:
Convert using Short.parseShort() : 100
Convert using Short.valueOf() : 100
Convert using new Short(String).intValue() : 100
Convert using DecimalFormat : 100


Comments