How to Convert String to Byte Array in Java


This example focuses on how to convert a string into a byte array in Java.

Source Code

package com.beginner.examples;

public class StringToByteExample {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "I love Java";
        byte[] bys = str.getBytes();
        for (int i = 0; i < bys.length; i++) {
            System.out.println(str.charAt(i) + "::byte::" + bys[i]);
        }
    }

}

Output:

I::byte::73
 ::byte::32
l::byte::108
o::byte::111
v::byte::118
e::byte::101
 ::byte::32
J::byte::74
a::byte::97
v::byte::118
a::byte::97
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments