Skip to content

Java convert String to byte example

This example shows how to convert string to byte in Java the parseByte method of the Byte wrapper class including out of the range values.

How to convert String to byte in Java?

To convert string to byte, use the parseByte method of the Byte wrapper class.

This method returns a byte primitive value by parsing the input string value.

Output

Important Note:

All the characters in the string must be digits, except for the first character of the string which can be a “-” (minus sign) to indicate the negative numeric value.

If any of the characters in the string (except for the first character, if it is a minus sign) is a non-digit character,  the NumberFormatException is thrown while converting.

Output

Here are some of the example string values and their possible byte outputs.

Please note that the “+” (plus sign) is allowed as the first character of the String in newer versions of Java. In older versions, if the string has a plus sign as a first character, the parseByte method throws the NumberFormatException.

Java byte data type range

The byte data type in Java is an 8 bit signed integer value. Range of the byte variable in Java is -128 to 127 (both inclusive). So the byte variable can have a minimum value of -128 while the maximum value it can hold is 127.

What happens when a string contains a number that is not in the range of byte?

When a string object contains a number that is not in the range of the byte data type and when we try to convert, the parseByte throws the NumberFormatException with a message saying that value is out of range as given below.

Output

This example is a part of the Java Basic Examples and Java Type conversion Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.