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,

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]+" ");

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

To convert byte[] array to String:

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.