Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

How to convert String to byte array and vice versa?

Category: Java

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.

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

Leave a Reply

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