Java Byte[] Array To String Conversion

In this tutorial, I am showing how to convert byte[] array to string using java.

Note: Here we are creating a new String new String(bytes, "UTF-8"); with utf-8 encoding, toString() method of String will not return the actual string but return the hash code of that string.

Java Byte[] Array To String Conversions

Here you can see the conversion from String to Byte[] array and Byte[] array to String are using the utf-8 encoding by using str.getBytes(StandardCharsets.UTF_8) and new String(byteValue, StandardCharsets.UTF_8); respectively You can see example below.

package com.javatips;

import java.nio.charset.StandardCharsets;

public class ByteArrayToString {

    public static void main(String[] args) {

	String str = "this is a string";
	byte[] byteValue = str.getBytes(StandardCharsets.UTF_8);

	System.out.println("str : " + str);
	System.out.println("byteValue : " + byteValue);
	System.out.println("byteValue.toString() : " + byteValue.toString());

	str = new String(byteValue, StandardCharsets.UTF_8);
	System.out.println("str : " + str);

    }

}


Output

str : this is a string
byteValue : [B@15db9742
byteValue.toString() : [B@15db9742
str : this is a string












Your email address will not be published. Required fields are marked *