Java Basic Examples

Java convert String to byte example

This example shows how to convert String to byte in Java. This example also shows how to convert String to byte primitive using Byte wrapper class.

How to convert String to byte in Java?

To convert String to byte, use parseByte method of Java Byte wrapper class.

This method returns 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 “-“(minus sign) to indicate the negative byte value.

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

Output

Here are some of the example String values and their possible byte output.

Please note that, “+” (plus sign) is allowed as a first character of the String in newer versions of Java. In older versions, if String has plus sign as a first character, parseByte method throws 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 minimum value of -128 while the maximum value it can hold is 127.

What happens when the String contains a number not in range of byte?

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

Output

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags