import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
// To verify that a String is serialized to a byte array with a specific
// encoding by re‑encoding the string using the same charset and comparing
// the resulting byte array to the one you want to validate.
// the same text + same charset ⇒ same byte sequence.
public class VerifyEncoding {
public static void main(String[] args) {
// The text we want to verify
String text = "Java Probabilist";
// The expected byte array (example: UTF‑8 encoding)
byte[] expected = text.getBytes(StandardCharsets.UTF_8);
// Choose the charset you want to verify
Charset charset = StandardCharsets.UTF_8;
// Encode the string using the chosen charset
byte[] actual = text.getBytes(charset);
// Compare the arrays
boolean matches = Arrays.equals(expected, actual);
// Output results
System.out.println("Text: " + text);
System.out.println("Charset: " + charset.name());
System.out.println("Expected bytes: " + Arrays.toString(expected));
System.out.println("Actual bytes: " + Arrays.toString(actual));
System.out.println("Match: " + matches);
}
}
/*
run:
Text: Java Probabilist
Charset: UTF-8
Expected bytes: [74, 97, 118, 97, 32, 80, 114, 111, 98, 97, 98, 105, 108, 105, 115, 116]
Actual bytes: [74, 97, 118, 97, 32, 80, 114, 111, 98, 97, 98, 105, 108, 105, 115, 116]
Match: true
*/