// Collection of code snippets by Arne VajhÃ¸j 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
public class UnicodeEscape {
    public static void main(String[] args) {
        test("abc");
        test("æøå");
        test("abc\u1234\u5678\u9ABCæøå");
        test("abcd\u044F\u0449,ert\u0431\u043B");
    }
    private static void test(String s) {
        String s2 = encode(s);
        System.out.println(s + "(" + s.length() + ") -> " +
                           s2 + "(" + s2.length() + ")");
    }
    public static String encode(String s) {
        StringBuffer sb = new StringBuffer("");
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if((c >= 0) && (c <=255)) {
                sb.append(c);
            } else {
                String hex = Integer.toHexString(c);
                sb.append("\\u" + "0000".substring(hex.length(), 4) + hex);
            }
        }
        return sb.toString();
    }
}
