How to convert Java String to byte[] Array


Post Banner

In order to convert a String to byte[] array in Java make use of the .getBytes() method from the String class,

Example:
public class JavaStringToByteArray {

    public static void main(String[] args) {

        String string = "Hello World!";
        byte[] byteArr = string.getBytes();

        for(int i = 1;i <byteArr.length; i++) {
            System.out.print(byteArr[i]+" ");
        }
    }
}
Output:

101 108 108 111 32 87 111 114 108 100 33 %



To convert byte[] array to String: https://code2care.org/java/convert-byte-arrry-to-string-in-java

-


Have Questions? Post them here!


Top Hashtags: