2020-04-13

Converting String to Byte Array Example

Converting String to Byte Array Example

Java program to convert a String to byte array and byte array to String.

Converting String to byte[] array in Java


String class has getBytes() method which used to convert String to byte array.

Other variants of getBytes():

byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) Deprecated.
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.

byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.


Java Program Example:


import java.util.Arrays;

public class StringToByte {

 public static void main(String[] args) {
  String str = "Example";
  byte[] b = str.getBytes();
  System.out.println("Array " + b);
  System.out.println("Array as String" + Arrays.toString(b));
 }

}

Output

Array [A@6yhs8B
Array as String[69, 120, 97, 109, 112, 108, 101]
As you can see here printing the byte array gives the memory address so used Arrays.toString in order to print the array values.


Java code to convert byte array to String


public class StringToByte {

 public static void main(String[] args) {
  String str = "Example String";
  // converting to byte array
  byte[] b = str.getBytes();
  
  // Getting the string from a byte array
  String s = new String (b);
  System.out.println("String - " + s);
 }
}

Output

String - Example String

No comments:

Post a Comment