Java Convert String To Byte Example

In this article, we will show you how to convert Java String to wrapper class Byte or primitive type byte. There are different ways we can convert Java String to Byte.

In this post, we will demonstrate converting Java String to wrapper class Byte or primitive type byte in 4 ways.
  1. Convert using Byte.parseByte()
  2. Convert using Byte.valueOf()
  3. Convert using new new Byte(String).byteValue()
  4. Convert using DecimalFormat

Java Convert String To Byte Example

This program demonstrates how to convert Java String to wrapper class Byte or primitive type byte. Refer the comments in below program are self-descriptive.
import java.text.DecimalFormat;
import java.text.ParseException;

/**
 * ConvertStringToByteExamples
 * @author javaguides.net
 *
 */
public class ConvertStringToByteExamples {
 public static void main(String[] args) {
  // Convert using IByte.parseByte
  String numberAsString = "100";
  byte number = Byte.parseByte(numberAsString);
  System.out.println("Convert using Byte.parseByte() : " + number);

  // Convert using Byte.valueOf()
  byte number1 = Byte.valueOf(numberAsString);
  System.out.println("Convert using Byte.valueOf() : " + number1);

  // Convert using new Integer(String).intValue()
  byte number2 = new Byte(numberAsString).byteValue();
  System.out.println("Convert using new Byte(String).intValue() : " + number2);

  // Convert using DecimalFormat
  DecimalFormat decimalFormat = new DecimalFormat("#");
  try {
   byte number3 = decimalFormat.parse(numberAsString).byteValue();
   System.out.println("Convert using DecimalFormat : " + number3);
  } catch (ParseException e) {
   System.out.println(numberAsString + " is not a valid number.");
  }
 }
}
Output:
Convert using Byte.parseByte() : 100
Convert using Byte.valueOf() : 100
Convert using new Byte(String).intValue() : 100
Convert using DecimalFormat : 100


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course