top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to convert String to byte array and vice versa in java?

0 votes
529 views
How to convert String to byte array and vice versa in java?
posted Jan 18, 2018 by Frank Lee

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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.

Here is a simple program showing how to convert String to byte array in java.

import java.util.Arrays;

public class StringToByteArray {

    public static void main(String[] args) {
        String str = "PANKAJ";
        byte[] byteArr = str.getBytes();
        // print the byte[] elements
        System.out.println("String to byte array: " + Arrays.toString(byteArr));
    }
}

Output:
String to byte array: [80, 65, 78, 75, 65, 74]

answer Jan 19, 2018 by Jon Deck
...