CodeBlanks Logo Icon CodeBlanks

Charset

Learn byte-character conversion with Charset.

Encoding with Charset

A Charset converts between strings and bytes. NIO provides this in the java.nio.charset package. The StandardCharsets class keeps common sets ready, such as UTF-8, UTF-16, and ISO-8859-1.

Example: "AB".getBytes(StandardCharsets.UTF_8) turns the string into UTF-8 bytes. UTF-8 is ASCII compatible, so 'A' and 'B' are one byte each. Non-ASCII letters take two bytes. Without the right set, strings look broken; so always state the encoding explicitly.

Encoding and decoding

Turning a string into bytes is called encoding; turning bytes into a string is decoding. NIO does this through a Charset object with encode and decode methods.

Example: Charset utf8 = StandardCharsets.UTF_8; ByteBuffer buf = utf8.encode("AB");. Here buf is a two-byte buffer. Conversely utf8.decode(buf) gives the string back. This cycle is the basis for processing bytes from files and networks as strings.

Practice Encode a string to UTF-8 bytes

Get a byte array with "AB".getBytes(StandardCharsets.UTF_8). Print the length property of the byte array with System.out.println.

Starter code

Main.java
// Encode to bytes with UTF_8
// Print with length

Sample solution

Main.java
import java.nio.charset.StandardCharsets;

public class CharsetDemo {
    public static void main(String[] args) {
        byte[] bytes = "AB".getBytes(StandardCharsets.UTF_8);
        System.out.println(bytes.length);
    }
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does StandardCharsets.UTF_8 define?

  • A character encoding Correct answer
  • A buffer
  • A channel
  • A path

Explanation: UTF_8 is a character encoding.

2 Match the Charset concepts

Term Meaning
StandardCharsets.UTF_8 Character encoding
getBytes String to bytes
Charset Encoding abstraction
new String Bytes to string

3 Encode with UTF_8

Question
"AB".getBytes(StandardCharsets.____);
Answer
"AB".getBytes(StandardCharsets.UTF_8);

Explanation: StandardCharsets.UTF_8 is the common encoding.

All lessons in Expert