In the last couple of examples, I have taught you how to convert String to Integer, Long, Double, Float, Boolean, and Byte in Java, and today I will show you how to convert String to Short in Java, but before that let's revise what is a short data type in Java. The short is an integral data type similar to the int but it only takes 2 bytes to store data as compared to 4 bytes required by an int variable. Since it takes only 2 bytes or 16 bits to store data, the range of short is also shorter than int. It ranges from -32,768 to 32767 (inclusive) or -2^15 to 2^15 -1. You might be wondering why the upper bound is 255 and the lower bound is -256 but that's because we have included zero in between.
The short primitive type is also a signed variable, which means the first bit is used to store the sign bit. The number is also represented in two's complement integer.
Now, similar to String to Integer example, there are 3 main ways to convert a String to a short primitive value or Short object in Java:
If you have used parseInt() or Integer.valueOf() method in past then you can understand how they behave, both parseShort() and Short.valueOf() behave in same way. If you are new to the Java world, you can further see these best Java Programming Courses learn more about Java fundamentals like those. In this article, our focus will be short,t but they are also very useful for converting other data types like int, char, boolean, long, floa,t and double in Java.
Here are some examples of parseShort() method:
This method throws an error if given String is invalid like contains characters other than a decimal digit and positive or negative sign or an out-of-range short value.
The method is also overloaded to support radix like. Short.parseShort(String value, int radix) which can be used to convert a binary, octal, or hexadecimal String to equivalent short value.
Here are some examples of Short.valueOf() method:
Because of caching, it reduces the number of the temporary Short object for the frequently used range. In short, use this method if you need a Short object rather than short value to avoid auto-boxing. See these free Java Programming courses to learn more about Auto-boxing and Unboxing in Java.
Here are some examples so Short constructors for converting a String object to Short in Java:
Even though it's simple, it's not the best way. As advised in Effective Java 3rd Edition by Joshua Bloch, it's better to use static factory methods like Short.valueOf() rather than constructor for creating objects. You can leverage caching to improve performance and control number of instances, particularly for an immutable class like Short.
But, if you need a short primitive value then you can directly use the Short.parseShort() method because it returns a short value and you don't require unboxing.
The Short constructor is even though a simple approach, it's not recommended because it directly couple your code with a Short constructor.
As suggested in Joshua Bloch's classic book Effective Java, The static factory method like valueOf() is better than the using constructor. It not only provides better performance by caching commonly used value but also decouple your code from the Short constructor.
If you remember, the object class provides a toString() method which is used to convert any Object to String and wrapper classes like Short or Integer is no different. In fact, they override toString() method to return their value as String.
Btw, you need a Short object to convert it to String. So, if you have a short primitive value then just assign that to a Short object and auto-boxing will automatically convert short primitive to a Short object. After that, you can call the toString() method.
Here is an example of converting short to String in Java:
You can then use this String to print or pass it to a method which needs a String value. If you are new to method and class then I suggest you to start learning Java from The Complete Java Masterclass, one of the most comprehensive Java course out there.
You can see that parseShort() returns a primitive short value, valueOf() returns a Short object, and you can even use the constructor of java.lang.Short class to convert a String to short in Java.
You can also see that the opposite conversion e.g. Short to String is, even more, easier because of toString() method of the Short class.
In the example, we have also learned that out-of-range short values e.g. integer values more than 32767 will throw java.lang.NumberFormatException in Java.
By the way, folks, if you want to learn more about the maximum and minimum range of different data type in Java then The Complete Java Masterclass is a good course to start with.
7.1. There are three main ways to convert a String to short in Java, parseShort(), valueOf() and Short constructor.
7.2. The parseShort() method actually parses the given String value and return a short primitive value.
7.3. Make sure you pass a valid short value. if you pass an integer value which is higher than the maximum short value i.e. 32767 then it will throw NumberFormatException as shown below:
7.4. Use the Short.parseShort() method if you need a short boolean value.
7.5. Use Short.valueOf() method if need a Short object as this method return a Short object as opposed to the short primitive value returned by the parseShort() method.
Even though it leverages the parsing logic of parseShort() method it is preferred because it can cache frequently used Short value to save memory.
7.6. Even though you can use the constructor of java.lang.Short class to convert a String to Short object, avoid that in favor of static factory method Short.valueOf(). If you want to learn more about why static factory method is better than the constructor, check the Item 1 from Effective Java 3rd Edition by Joshua Bloch.
7.7. The java.lang.Short class also provides methods to convert a decimal short value into octal or hexadecimal. It has overloaded parseShort(String value, int radix) and valueOf(String value, int radix) which takes a radix to convert given String to Short in other number systems.
7.8. Short is a wrapper class for short primitive value, which takes 2 bytes of 16-bit to store numeric integral value. The minimum short value is -32768 and the maximum value is 32767.
That's all about how to convert String to Short in Java. In a nutshell, if you need a short primitive value, just use Short.parseShort() method and if you need a Short wrapper object, prefer Short.valueOf() method. Though, be careful with the range, passing an out-of-range integer value to convert short may result in NumberFormatException.
Thanks for reading this article so far. If you like this core Java tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.
The short primitive type is also a signed variable, which means the first bit is used to store the sign bit. The number is also represented in two's complement integer.
Now, similar to String to Integer example, there are 3 main ways to convert a String to a short primitive value or Short object in Java:
- Using Short.parseShort() method
- Using Short.valueOf() method
- Using Short Constructor
If you have used parseInt() or Integer.valueOf() method in past then you can understand how they behave, both parseShort() and Short.valueOf() behave in same way. If you are new to the Java world, you can further see these best Java Programming Courses learn more about Java fundamentals like those. In this article, our focus will be short,t but they are also very useful for converting other data types like int, char, boolean, long, floa,t and double in Java.
1. Short.parseShort() Example
This is the actual method which contains parsing logic for converting String to short in Java. It accepts a String and returns a short primitive value. The digits must be in decimal format and the first character can be a + or - (minus) sign to indicate positive and negative numbers.Here are some examples of parseShort() method:
short s = Short.parseShort("101"); // returns 101 short s = Short.parseShort("+121"); // returns 121 short s = Short.parseShort("-121"); // returns -121 short s = Short.parseShort("32768"); // throw error
This method throws an error if given String is invalid like contains characters other than a decimal digit and positive or negative sign or an out-of-range short value.
The method is also overloaded to support radix like. Short.parseShort(String value, int radix) which can be used to convert a binary, octal, or hexadecimal String to equivalent short value.
2. Short.valueOf() Example
You can use this method if you need a Short object rather than a short value. This method internally uses the parseShort() method for parsing but on top of that, it provides caching. Similar to Integer.valueOf() method this one also caches Short values in the range -128 to 127.Here are some examples of Short.valueOf() method:
Short object = Short.valueOf("101"); // returns 101 Short object = Short.valueOf("+121"); // returns 121 Short object = Short.valueOf("-121"); // returns -121 Short object = Short.valueOf("32768"); // throw error
Because of caching, it reduces the number of the temporary Short object for the frequently used range. In short, use this method if you need a Short object rather than short value to avoid auto-boxing. See these free Java Programming courses to learn more about Auto-boxing and Unboxing in Java.
3. String to Short using Constructor
The most simple and obvious way to convert a String value to a Short object in Java is by using the new Short(String value) constructor, which takes a String object and returns an equivalent short value. This method also follows all the parsing rules followed by parseShort() method, in fact, it internally uses that method but unlike valueOf() method it returns a new Short object every time you call it.Here are some examples so Short constructors for converting a String object to Short in Java:
Short value = new Short("1001"); //returns 1001 Short value = new Short("+2001"); //returns positive 2001 Short value = new Short("-2001"); //returns negative 2001 Short value = new Short("32768"); //throws error
Even though it's simple, it's not the best way. As advised in Effective Java 3rd Edition by Joshua Bloch, it's better to use static factory methods like Short.valueOf() rather than constructor for creating objects. You can leverage caching to improve performance and control number of instances, particularly for an immutable class like Short.
4. the Best way to convert String to Short in Java?
The preferred method is always the valueOf() method because it can cache frequently used values and save memory by returning immutable objects.But, if you need a short primitive value then you can directly use the Short.parseShort() method because it returns a short value and you don't require unboxing.
The Short constructor is even though a simple approach, it's not recommended because it directly couple your code with a Short constructor.
As suggested in Joshua Bloch's classic book Effective Java, The static factory method like valueOf() is better than the using constructor. It not only provides better performance by caching commonly used value but also decouple your code from the Short constructor.
5. Short to String
So far, we have looked at the examples of converting a String object to Short object or primitive in Java but what about the opposite? how do you convert a Short object or primitive to a String? Well, that's not difficult and in most cases done by Java automatically.If you remember, the object class provides a toString() method which is used to convert any Object to String and wrapper classes like Short or Integer is no different. In fact, they override toString() method to return their value as String.
Btw, you need a Short object to convert it to String. So, if you have a short primitive value then just assign that to a Short object and auto-boxing will automatically convert short primitive to a Short object. After that, you can call the toString() method.
Here is an example of converting short to String in Java:
Short value = 123; // short primitive to Short object String str = value.toString(); // Short object to String
You can then use this String to print or pass it to a method which needs a String value. If you are new to method and class then I suggest you to start learning Java from The Complete Java Masterclass, one of the most comprehensive Java course out there.
6. Java Program to Convert String to Short
Here is our sample Java program to demonstrate how you can use the parseShort(), valueOf() and constructor of java.lang.Short class to convert a String value in Java. You will also learn the opposite i.e. converting a Short value to String in Java.package tool; /** * * A simple Java Program to convert a String to short primitive * or Short wrapper * object in Java. */ public class Hello { public static void main(String[] args) { // parseShort() Example - String to short primitive value short s = Short.parseShort("101"); System.out.println("short primitive value from string: " + s); // Short.valueOf() Example - String to Short wrapper object Short sObject = Short.valueOf("151"); System.out.println("Short wrapper value from string: " + sObject); // Short constructor example Short value = new Short("251"); System.out.println("Short object from string: " + value); // Short to String Example using Short.toString() String str = sObject.toString(); System.out.println("String value from Short object: " + str); // Out-of-range short value will throw error short outOfRange = Short.parseShort("32768"); } } Output short primitive value from string: 101 Short wrapper value from string: 151 Short object from string: 251 String value from Short object: 151 Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"32768" Radix:10 at java.lang.Short.parseShort(Short.java:120) at java.lang.Short.parseShort(Short.java:144) at tool.Hello.main(Hello.java:33)
You can see that parseShort() returns a primitive short value, valueOf() returns a Short object, and you can even use the constructor of java.lang.Short class to convert a String to short in Java.
You can also see that the opposite conversion e.g. Short to String is, even more, easier because of toString() method of the Short class.
In the example, we have also learned that out-of-range short values e.g. integer values more than 32767 will throw java.lang.NumberFormatException in Java.
By the way, folks, if you want to learn more about the maximum and minimum range of different data type in Java then The Complete Java Masterclass is a good course to start with.
7. Important Points
Now that you know how to convert a String to Short in Java, let's revise some of the important points7.1. There are three main ways to convert a String to short in Java, parseShort(), valueOf() and Short constructor.
7.2. The parseShort() method actually parses the given String value and return a short primitive value.
7.3. Make sure you pass a valid short value. if you pass an integer value which is higher than the maximum short value i.e. 32767 then it will throw NumberFormatException as shown below:
short value = Short.parseShort("34000");
Exception in thread "main" java.lang.NumberFormatException:
Value out of range. Value:"34000" Radix:10
at java.lang.Short.parseShort(Short.java:120)
at java.lang.Short.parseShort(Short.java:144)
at tool.Hello.main(Hello.java:14)
7.4. Use the Short.parseShort() method if you need a short boolean value.
7.5. Use Short.valueOf() method if need a Short object as this method return a Short object as opposed to the short primitive value returned by the parseShort() method.
Even though it leverages the parsing logic of parseShort() method it is preferred because it can cache frequently used Short value to save memory.
7.6. Even though you can use the constructor of java.lang.Short class to convert a String to Short object, avoid that in favor of static factory method Short.valueOf(). If you want to learn more about why static factory method is better than the constructor, check the Item 1 from Effective Java 3rd Edition by Joshua Bloch.
7.7. The java.lang.Short class also provides methods to convert a decimal short value into octal or hexadecimal. It has overloaded parseShort(String value, int radix) and valueOf(String value, int radix) which takes a radix to convert given String to Short in other number systems.
7.8. Short is a wrapper class for short primitive value, which takes 2 bytes of 16-bit to store numeric integral value. The minimum short value is -32768 and the maximum value is 32767.
That's all about how to convert String to Short in Java. In a nutshell, if you need a short primitive value, just use Short.parseShort() method and if you need a Short wrapper object, prefer Short.valueOf() method. Though, be careful with the range, passing an out-of-range integer value to convert short may result in NumberFormatException.
Thanks for reading this article so far. If you like this core Java tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.