Java – String to Byte[] Arrays conversion

In this article, we will discuss how to convert String to Byte[] array in Java

1. Byte:

  • Size is 1 byte
  • Its range is -128 to 127

Q) Why we need to convert String into Byte[] Arrays ?

  • Sometimes, it is important to convert String to byte array for base64 computation

2. String to byte[] array using getBytes() method:

  • This method can be used to convert String into primitive byte[] array
  • Note: The value range should be within -128 to 127

Method signature:

public byte[] getBytes(String charsetName);

ConvertStringToByteArrayUsingGetBytesMethod.java

package in.bench.resources.string.to.bytes.conversion;

import java.util.Arrays;

public class ConvertStringToByteArrayUsingGetBytesMethod {

	public static void main(String[] args) {

		// String
		String encPassword = "ThisIsMyPassWord";

		// original text
		System.out.println("Original String : "
				+ encPassword);

		// converting String to byte[] array
		byte[] byteArray = encPassword.getBytes();

		// 1. printing in Byte format after conversion
		System.out.println("\nConverted"
				+ " byte[] array in Byte format : "
				+ byteArray);

		// 2. Returns string representation of  specified array
		System.out.println("\nConverted"
				+ " byte[] array in Array format : "
				+ Arrays.toString(byteArray));
	}
}

Output:

Original String :
	ThisIsMyPassWord

Converted byte[] array in Byte format :
	[B@1615099

Converted byte[] array in Array format :
	[84, 104, 105, 115, 73, 115, 77, 121,
	 80, 97, 115, 115, 87, 111, 114, 100]

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Byte Array to String conversion
Java - Byte to String conversion in 5 ways