Convert Byte to String in Java

In Java, converting a byte value to its equivalent String representation can be done using the String.valueOf() method or concatenation with an empty string. Let's explore both methods with examples. 

1. Using String.valueOf() Method 

The String.valueOf(byte b) method is a straightforward way to convert a byte value to its String representation. 

Example:

public class ByteToStringExample {
    public static void main(String[] args) {
        byte byteValue = 42;
        String stringValue = String.valueOf(byteValue);

        System.out.println("Byte Value: " + byteValue);
        System.out.println("String Value: " + stringValue);
    }
}

Output:

Byte Value: 42
String Value: 42

2. Concatenation with an Empty String 

You can also convert a byte to a String by concatenating it with an empty string. 

Example:

public class ByteToStringExample {
    public static void main(String[] args) {
        byte byteValue = -128;
        String stringValue = "" + byteValue;

        System.out.println("Byte Value: " + byteValue);
        System.out.println("String Value: " + stringValue);
    }
}

Output:

Byte Value: -128
String Value: -128

Conclusion 

Converting a byte to a String in Java is a simple task, and you have multiple methods available to achieve it. Whether you use String.valueOf() or concatenation with an empty string, you will get a String representation of the original byte value.

Related String Conversion Examples

Comments