×

Java Programs

Java Practice

Java program to convert string to byte

Given/input a string, we have to convert it into byte.
Submitted by Nidhi, on March 15, 2022

Problem statement

In this program, we will read a numeric string from the user and convert the input string into a byte using 2 different methods.

Java program to convert string to byte

The source code to convert string to byte is given below. The given program is compiled and executed successfully.

// Java program to convert 
// string to byte

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);
    String str;

    System.out.print("Enter string: ");
    str = X.next();

    byte byteValue = 0;

    //Using byteValue() method.
    byteValue = Byte.valueOf(str).byteValue();
    System.out.println("Byte value: " + byteValue);

    //Using parseByte() method.
    byteValue = Byte.parseByte(str);
    System.out.println("Byte value: " + byteValue);
  }
}

Output

Enter string: 123
Byte value: 123
Byte value: 123

Explanation

In the above program, we imported java.util.Scanner to read input from the user. And, created a Main class that contains a method main().

The main() method is the entry point for the program, here we read a string from the user using the Scanner class. Then we converted the input string into a byte using two different methods and printed the result.

Java Conversion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.