A String in Java may contain a numeric value as text, while byte is a primitive data type used to store small integer values. Java provides methods in the Byte wrapper class to convert a numeric String into a byte.
- The byte data type stores values from -128 to 127.
- The input String must contain a valid byte value; otherwise, the conversion throws a NumberFormatException.
- Byte.parseByte() returns a primitive byte, while Byte.valueOf() returns a Byte object.
Examples:
Input: String = "25"
Output: 25Input: String = "-100"
Output: -100
Methods to Convert String to Byte
1. Using Byte.parseByte() Method
The parseByte() method of the Byte class converts a numeric String into a primitive byte value.
Syntax
Byte.parseByte(str);
public class Main {
// Convert String to byte
public static byte convertStringToByte(String str) {
return Byte.parseByte(str);
}
public static void main(String[] args) {
String stringValue = "25";
byte byteValue = convertStringToByte(stringValue);
System.out.println(
stringValue + " after converting into byte = "
+ byteValue
);
}
}
Output
25 after converting into byte = 25
Explanation: Byte.parseByte() reads the numeric value from the String and returns its equivalent primitive byte value. If the String does not contain a valid byte value, it throws NumberFormatException.
2. Using Byte.valueOf() Method
The valueOf() method of the Byte class converts a numeric String into a Byte object. The returned Byte object can also be automatically unboxed when assigned to a primitive byte.
Syntax
Byte.valueOf(str);
public class Main {
// Convert String to byte
public static byte convertStringToByte(String str) {
return Byte.valueOf(str);
}
public static void main(String[] args) {
String stringValue = "50";
byte byteValue = convertStringToByte(stringValue);
System.out.println(
stringValue + " after converting into byte = "
+ byteValue
);
}
}
Output
50 after converting into byte = 50
Explanation: Byte.valueOf() converts the numeric String into a Byte object. In this program, Java automatically converts the returned Byte object into a primitive byte through unboxing.
Handling Invalid Input
If the String contains a value outside the byte range or a non-numeric value, Java throws NumberFormatException.
public class Main {
public static void main(String[] args) {
String str = "200";
try {
byte value = Byte.parseByte(str);
System.out.println("Byte value: " + value);
} catch (NumberFormatException e) {
System.out.println("Invalid byte value: " + str);
}
}
}
Output
Invalid byte value: 200
Explanation: Here, 200 cannot be represented by a Java byte because the valid range is -128 to 127.