0 votes
in JAVA by

How to convert String to byte array and vice versa?

1 Answer

0 votes
by
We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

Check this post for String to byte array example.

 

String API is already loaded with getBytes() methods that convert a string into bytes array.

You can anyone of the below methods.

public byte[] getBytes()

public byte[] getBytes(Charset charset)

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

 

String to byte array example:

package com.javaprogramto.arrays.bytearray;

public class StrintToByteArrayExample {

public static void main(String[] args) {

// creating string

String string = "javaprogrmto.com";

// string to byte array

byte[] array1 = string.getBytes();

// printing byte array

for (int i = 0; i < array1.length; i++) {

System.out.print(" " + array1[i]);

}

}

}

 

Output:

 106 97 118 97 112 114 111 103 114 109 116 111 46 99 111 109

 

It is good practice to use the other overloaded methods for getBytes().

getBytes() method uses the internally default character set using Charset.defaultCharset() and it is platform dependent.

You can pass the specific character set name to this method.

// creating string

String string = "javaprogrmto.com";

String characterSetName = "ASCII";

try {

byte[] array2 = string.getBytes(characterSetName);

// printing byte array

for (int i = 0; i < array2.length; i++) {

System.out.print(" " + array1[i]);

}

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

Output:

 106 97 118 97 112 114 111 103 114 109 116 111 46 99 111 109

Related questions

0 votes
asked Mar 16, 2021 in JAVA by Robindeniel
0 votes
asked Mar 16, 2021 in JAVA by Robindeniel
...