Java – String to short conversion in 3 ways

In this article, we will discuss various ways to convert String to short (or Short) in Java

1. Short:

  • Size is 2 bytes
  • Its range is -32,768 to 32,767

2. Various ways to convert String to short:

  1. Using Short.parseShort(“strValue”);
  2. Using Short.valueOf(“strValue”);
  3. Create Short object and pass string as constructor-argument

Read String class in detail with example

Let us move forward and discuss all possible ways to convert String to Short in Java

2.1 Using Short.parseShort(“strValue”) method

  • This method can be used to convert String which constitutes of only numbers (or digits) into primitive short data-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.1 example

Method signature:

public static short parseShort(String s)
		throws NumberFormatException;

ConvertStringToShortUsingParseShortMethod.java

package in.bench.resources.string.to.shorts.conversion;

public class ConvertStringToShortUsingParseShortMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "25698";

		// 1. converting String to short
		short shortValue1 = Short.parseShort(str1);
		System.out.println("1. Converted short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-31694";

		// 2. converting String to int
		short shortValue2 = Short.parseShort(str2);
		System.out.println("\n2. Converted short value is : "
				+ shortValue2);
	}
}

Output:

1. Converted short value is : 25698

2. Converted short value is : -31694

2.2 Using Short.valueOf(“strValue”) method

  • This method can be used to convert String which constitutes of only numbers (or digits) into Short wrapper-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.2 example

Method signature:

public static Short valueOf(String s)
		throws NumberFormatException;

ConvertStringToShortUsingValueOfMethod.java

package in.bench.resources.string.to.shorts.conversion;

public class ConvertStringToShortUsingValueOfMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "32120";

		// 1. converting String to Short
		Short shortValue1 = Short.valueOf(str1);
		System.out.println("1. Converted Short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-11256";

		// 2. converting String to Short
		Short shortValue2 = Short.valueOf(str2);
		System.out.println("\n2. Converted Short value is : "
				+ shortValue2);
	}
}

Output:

1. Converted Short value is : 32120

2. Converted Short value is : -11256

2.3 Create Short object and pass string as constructor-argument

  • Here, we will create new Short object with String as constructor-argument
  • After creating new Short object by passing string value, then invoke shortValue() method for converting String to primitive short data-type
  • Passed string to constructor-argument should constitutes of only numbers (or digits)
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.3 example

Method signature:

public Short(String s) throws NumberFormatException;

public short shortValue();

ConvertStringToShortUsingShortValueMethod.java

package in.bench.resources.string.to.shorts.conversion;

public class ConvertStringToShortUsingShortValueMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "20569";

		// 1. converting String to short
		// by creating new Short Object
		Short short1 = new Short(str1);
		short shortValue1 = short1.shortValue();
		System.out.println("1. Converted short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-9568";

		// 2. converting String to short
		// by creating new Short Object
		Short short2 = new Short(str2);
		short shortValue2 = short2.shortValue();
		System.out.println("\n2. Converted short value is : "
				+ shortValue2);
	}
}

Output:

1. Converted short value is : 20569

2. Converted short value is : -9568

Exception scenarios:

  • In all above 3 cases, whenever string isn’t properly formatted to convert String to short or Short, then NumberFormatException will be thrown
  • We will see, what happens if string isn’t correctly formatted for all 3 ways of conversion
  • For case 4 i.e.; E.4, we will convert out of range value for short

3. Exception scenario:

  • handle exception properly in all 3 ways
  • otherwise NumberFormatException will be thrown for incorrect string values (or not correctly formatted string)
  • and terminates program abruptly
  • we will see 3 different examples for all cases with E.1, E.2 and E.3
  • We will also see one example for out of range value with case E.4

3.1 Handle NumberFormatException while converting String to short using Short.parseShort() method

ParseShortMethodThrowsNFE.java

package in.bench.resources.string.to.shorts.conversion;

public class ParseShortMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "25ben";

		// 1. converting String to short
		short shortValue1 = Short.parseShort(str1);
		System.out.println("1. Converted short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-31res";

		// 2. converting String to int
		short shortValue2 = Short.parseShort(str2);
		System.out.println("\n2. Converted short value is : "
				+ shortValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	For input string: "25ben"
	at java.lang.NumberFormatException.forInputString(
			NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Short.parseShort(Short.java:118)
	at java.lang.Short.parseShort(Short.java:144)
	at in.bench.resources.string.to.shorts.conversion
	.ParseShortMethodThrowsNFE
	.main(ParseShortMethodThrowsNFE.java:11)

3.2 Handle NumberFormatException while converting String to short using Short.valueOf() method

ShortValueOfMethodThrowsNFE.java

package in.bench.resources.string.to.shorts.conversion;

public class ShortValueOfMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "32gen";

		// 1. converting String to Short
		Short shortValue1 = Short.valueOf(str1);
		System.out.println("1. Converted Short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-11pin";

		// 2. converting String to Short
		Short shortValue2 = Short.valueOf(str2);
		System.out.println("\n2. Converted Short value is : "
				+ shortValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	For input string: "32gen"
	at java.lang.NumberFormatException.forInputString(
			NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Short.parseShort(Short.java:118)
	at java.lang.Short.valueOf(Short.java:174)
	at java.lang.Short.valueOf(Short.java:200)
	at in.bench.resources.string.to.shorts.conversion
	.ShortValueOfMethodThrowsNFE
	.main(ShortValueOfMethodThrowsNFE.java:11)

3.3 Handle NumberFormatException while converting String to short using shortValue() method

ShortValueMethodThrowsNFE.java

package in.bench.resources.string.to.shorts.conversion;

public class ShortValueMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "20Goo";

		// 1. converting String to short
		// by creating new Short Object
		Short short1 = new Short(str1);
		short shortValue1 = short1.shortValue();
		System.out.println("1. Converted short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-9Ora";

		// 2. converting String to short
		// by creating new Short Object
		Short short2 = new Short(str2);
		short shortValue2 = short2.shortValue();
		System.out.println("\n2. Converted short value is : "
				+ shortValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	For input string: "20Goo"
	at java.lang.NumberFormatException.forInputString(
			NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Short.parseShort(Short.java:118)
	at java.lang.Short.<init>(Short.java:321)
	at in.bench.resources.string.to.shorts.conversion
	.ShortValueMethodThrowsNFE
	.main(ShortValueMethodThrowsNFE.java:11)

3.4 For out of range value for Short i.e.; outside prescribed range of -32,768 to 32,767

ShortOutOfRangeValueException.java

package in.bench.resources.string.to.shorts.conversion;

public class ShortOutOfRangeValueException {

	public static void main(String[] args) {

		// String with only digits outside short range
		String str1 = "32786";

		// 1. converting String to short
		short shortValue1 = Short.parseShort(str1);
		System.out.println("1. Converted short value is : "
				+ shortValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-32856";

		// 2. converting String to int
		short shortValue2 = Short.parseShort(str2);
		System.out.println("\n2. Converted short value is : "
				+ shortValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	Value out of range. Value:"32786" Radix:10
	at java.lang.Short.parseShort(Short.java:120)
	at java.lang.Short.parseShort(Short.java:144)
	at in.bench.resources.string.to.shorts.conversion
	.ShortOutOfRangeValueException
	.main(ShortOutOfRangeValueException.java:11)

Q) What if we want to convert primitive short data-type to Short wrapper type or vice-versa ?

  • Auto-boxing feature available from Java 1.5 version
  • So, converting primitive data-type to wrapper-type can easily be done, by directly assigning
  • Let’s see one example based on this auto-boxing feature

4. Auto-boxing and un-boxing feature from Java 1.5 version:

  • parseShort() method returns primitive short type but it can be easily used as Short wrapper-type
  • as auto-boxing feature helps to convert primitive type to wrapper-types
  • similarly, Short.valueOf() method returns Short wrapper-type but it can also be used as primitive short data-type

AutoBoxingFeatureForShortConversion.java

package in.bench.resources.string.to.shorts.conversion;

public class AutoBoxingFeatureForShortConversion {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "32120";

		// string to short conversion
		short shortValue1 = Short.parseShort(str1);

		// 1. Auto-Boxing - converting short to Short
		Short shortAutoBoxing = shortValue1;
		System.out.println("1. Auto-Boxing : "
				+ shortAutoBoxing);

		// String with only digits and a minus sign (-)
		String str2 = "-15936";

		// string to Short conversion
		Short shortValue2 = Short.valueOf(str2);

		// 1. Un-Boxing - converting Short to short
		short shortUnBoxing = shortValue2;
		System.out.println("\n2. Un-Boxing   : "
				+ shortUnBoxing);
	}
}

Output:

1. Auto-Boxing : 32120

2. Un-Boxing   : -15936

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Short to String conversion in Java - 5 ways
Java - Byte Array to String conversion