Java Data Type How to - Encode UTF String








Question

We would like to know how to encode UTF String.

Answer

import java.nio.charset.Charset;
//from w  w w  . j a  v  a 2  s .c  o  m
public class Main {
    public static void main(String[] args) throws Exception {
        String pound = "\u00a3";
        byte[] bytes = pound.getBytes(Charset.forName("UTF-8"));
        for (byte b : bytes) {
            System.out.println(b & 0xff); // 194, 163
        }
    }
}