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!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
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.