Write Java program to Convert string to byte


This is a Java program that demonstrates how to convert a string to a byte using two different methods: Byte.valueOf().byteValue() and Byte.parseByte().

  • In this program, a Scanner object named input is created to read input from the user. The program prompts the user to enter a number and reads the input as a string using the Scanner.next() method. The string is then printed using the System.out.println() method.
  • Next, a byte variable byte_Val is initialized to 0.
  • The program then uses the Byte.valueOf().byteValue() method to convert the string to a byte. This method first calls the Byte.valueOf() method, which returns a Byte object that represents the value of the string.
  • The Byte.byteValue() method is then called on the returned object to get the byte value. The byte value is then assigned to the byte_Val variable, and the value is printed using the System.out.println() method.
  • Finally, the program uses the Byte.parseByte() method to convert the string to a byte. This method directly parses the string and returns the byte value. The byte value is then assigned to the byte_Val variable, and the value is printed using the System.out.println() method.

Source Code

import java.util.Scanner;
public class StringToByte
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		String str;
		System.out.print("Enter the Number : ");
		str = input.next();
		System.out.println("String Value : " + str);
 
		byte byte_Val = 0;
 
		//byteValue() Method 1
		byte_Val = Byte.valueOf(str).byteValue();
		System.out.println("Byte value Using byteValue() Method : " + byte_Val);
 
		//parseByte() Method 2
		byte_Val = Byte.parseByte(str);
		System.out.println("Byte value Using parseByte() Method : " + byte_Val);
	}
}

Output

Enter the Number : 103
String Value : 103
Byte value Using byteValue() Method : 103
Byte value Using parseByte() Method : 103