Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

StandardCharsets — choosing a text encoding explicitly

StandardCharsets provides ready-made Charset objects for standard encodings required by the Java platform. Use StandardCharsets.UTF_8 or StandardCharsets.UTF_16BE to specify explicitly how text becomes bytes and how bytes become text.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

import java.nio.charset.StandardCharsets;
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String restored = new String(bytes, StandardCharsets.UTF_8);
byte[] bigEndian = text.getBytes(StandardCharsets.UTF_16BE);

java.nio.charset.StandardCharsets contains public static final constants of type Charset, not encoding names of type String. Encoding converts text into bytes; decoding reconstructs text from bytes. The encodings represented by these constants are guaranteed to be supported by every Java platform implementation.

StandardCharsets.UTF_8 selects UTF-8. StandardCharsets.UTF_16BE selects UTF-16 with the more significant byte of each 16-bit unit first. Do not confuse UTF_16BE with UTF_16: when encoding, UTF_16BE does not add a byte-order mark (BOM), whereas UTF_16 adds a BOM and uses big-endian order. When decoding with UTF_16BE, an initial BOM remains a U+FEFF character rather than controlling byte order.

Pass the constant explicitly to text.getBytes(StandardCharsets.UTF_8) and new String(bytes, StandardCharsets.UTF_8). When reading, choose the encoding matching the actual data format; the constant does not detect it automatically. An explicit choice removes this conversion's dependency on the default charset.

The example encodes A\u0105 in two ways and prints the bytes in hexadecimal. The expected output is 41c485, 00410105, true, true, each on a separate line. The final two lines check that decoding with the same encoding reconstructs the text.

Examples

import java.nio.charset.StandardCharsets;
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) {
        String text = "A\u0105";
        byte[] utf8 = text.getBytes(StandardCharsets.UTF_8);
        byte[] utf16be = text.getBytes(StandardCharsets.UTF_16BE);

        System.out.println(HexFormat.of().formatHex(utf8));
        System.out.println(HexFormat.of().formatHex(utf16be));
        System.out.println(text.equals(new String(utf8, StandardCharsets.UTF_8)));
        System.out.println(text.equals(new String(utf16be, StandardCharsets.UTF_16BE)));
    }
}

Result

41c485
00410105
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources