How to Convert a String value to Byte value in Java with Examples
Last Updated :
29 Jan, 2020
Given a String “str” in Java, the task is to convert this string to byte type.
Examples:
Input: str = "1"
Output: 1
Input: str = "3"
Output: 3
Approach 1: (Naive Method)
One method is to traverse the string and add the numbers one by one to the byte type. This method is not an efficient approach.
Approach 2: (Using Byte.parseByte() method)
The simplest way to do so is using parseByte() method of Byte class in java.lang package. This method takes the string to be parsed and returns the byte type from it. If not convertible, this method throws error.
Syntax:
Byte.parseByte(str);
Below is the implementation of the above approach:
Example 1: To show successful conversion
class GFG {
public static byte convertStringToByte(String str)
{
return Byte.parseByte(str);
}
public static void main(String[] args)
{
String stringValue = "1" ;
byte byteValue;
byteValue = convertStringToByte(stringValue);
System.out.println(
stringValue
+ " after converting into byte = "
+ byteValue);
}
}
|
Output:
1 after converting into byte = 1
Approach 3: (Using Byte.valueOf() method)
The valueOf() method of Byte class converts data from its internal form into human-readable form.
Syntax:
Byte.valueOf(str);
Below is the implementation of the above approach:
Example 1: To show successful conversion
class GFG {
public static byte convertStringToByte(String str)
{
return Byte.valueOf(str);
}
public static void main(String[] args)
{
String stringValue = "1" ;
byte byteValue;
byteValue = convertStringToByte(stringValue);
System.out.println(
stringValue
+ " after converting into byte = "
+ byteValue);
}
}
|
Output:
1 after converting into byte = 1
Share your thoughts in the comments
Please Login to comment...