What is NumberUtils.toByte() in Java?
toByte() is a NumberUtils class that is used to convert the given string to a byte value. One variant of the method accepts a default value that is returned if the conversion fails.
How to import NumberUtils
The definition of NumberUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the NumberUtils class as follows.
import org.apache.commons.lang3.math.NumberUtils;
Syntax
public static byte toByte(final String str, final byte defaultValue)
Parameters
final String str: The string to convert.final byte defaultValue: The default value to return.
Return value
This method returns a byte value. Otherwise, the default value is returned if the conversion fails.
Overloaded methods
public static byte toByte(final String str)
Code
import org.apache.commons.lang3.math.NumberUtils;public class Main{public static void main(String[] args){// Example 1String stringToConvert = "6";byte defaultValue = 2;System.out.printf("The output of the method NumberUtils.toByte(%s, %s) is %s", stringToConvert, defaultValue, NumberUtils.toByte(stringToConvert, defaultValue));System.out.println();// Example 2stringToConvert = "233sdf";defaultValue = 2;System.out.printf("The output of the method NumberUtils.toByte(%s, %s) is %s", stringToConvert, defaultValue, NumberUtils.toByte(stringToConvert, defaultValue));System.out.println();}}
Example 1
stringToConvert = "6"defaultValue = 2
The method returns 6 as the conversion is successful.
Example 2
stringToConvert = "233sdf"defaultValue = 2
The method returns 2 as the conversion is unsuccessful.
Output
The output of the code will be as follows:
The output of the method NumberUtils.toByte(6, 2) is 6
The output of the method NumberUtils.toByte(233sdf, 2) is 2