Java Data Type How to - Convert String to byte array by Encoding








Question

We would like to know how to convert String to byte array by Encoding.

Answer

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
//from w w  w.  ja v  a 2  s.  co  m

public class Main {
  public static void main(String[] args) throws UnsupportedEncodingException {
    String s = "Hello world";
    byte[] b = s.getBytes("US-ASCII");
    System.out.println(Arrays.toString(b));
  }
}

The code above generates the following result.