// Week 4 – Character encoding: char, code point, UTF-8 bytes
// Run: java Encoding.java
import java.nio.charset.StandardCharsets;

public class Encoding {
    public static void main(String[] args) {
        String s = "Aé世😀";

        // Internally a Java String consists of UTF-16 code units (char).
        // Characters outside the BMP (e.g. emojis) take TWO chars (a surrogate pair).
        System.out.println("length()          = " + s.length());                         // 5
        System.out.println("codePointCount()  = " + s.codePointCount(0, s.length()));   // 4
        System.out.println("number of UTF-8 bytes = " + s.getBytes(StandardCharsets.UTF_8).length); // 10

        // Iterating by code point – every "real" character is visited once
        s.codePoints().forEach(cp ->
                System.out.printf("  %s  U+%04X  (%d)%n", new String(Character.toChars(cp)), cp, cp));

        // Printing the UTF-8 bytes
        System.out.print("UTF-8: ");
        for (byte b : s.getBytes(StandardCharsets.UTF_8)) System.out.printf("%02X ", b);
        System.out.println();

        // Iterating char by char cuts the emoji into two "halves"!
        System.out.print("char by char: ");
        for (int i = 0; i < s.length(); i++) System.out.printf("%04X ", (int) s.charAt(i));
        System.out.println();

        // ASCII arithmetic
        char c = 'c';
        System.out.println("'c' - 'a' = " + (c - 'a') + " (position of the letter in the alphabet)");
        System.out.println("'7' - '0' = " + ('7' - '0') + " (digit character -> value)");
    }
}
