Convert String to short: Sometimes, we obtain the values in string format in Java. Printing the value is no problem (as long as user gets the same output) as it prints the same value as data type prints.
For example, a short value is obtained in string format as in command-line arguments or from TextField's getText() method. The string value is to be converted into short format to use in caluclations as strings (or any objects in Java) cannnot be multiplied or used in any arithmetic operation. To convert, casting does not work as string and short are incompatable for conversion either implicitly or explicitly. It requires extra effort in coding known as "parsing operation". Parsing operation involves the usage of a wrapper class and parseXXX() method. For string to short conversion, it is required Short class and parseShort() method and explained in the following program.
Example on String to short
public class Conversions
public static void main(String args)
String str = "10";
short s1 = Short.parseShort(str); // parsing operation, conversion
System.out.println("10 in String form: " + str);
System.out.println("10 in Short form: " + s1);
System.out.println("Square of short 10: " + s1 * s1); // using in multiplication
Output screenshot on String to short Example
parseShort() is a method of wrapper class Short which converts string str to short s1. Now s1 can be used in arithmetic operations.
Using the same technique, it is possible to convert string to other data types byte, int, long, float, double, character and boolean.
Note: The other way short to string is also possible.