Sub topic 13
Encoding and Decoding Bytes
A Java String holds text. But files and network connections store or send data as bytes. A byte is a group of eight bits, the small units used to store data.
Encoding turns text into bytes. Decoding turns those bytes back into text. You need both steps when text travels between Java and a file, a network connection, or another program.
Choose a character set
A character set, or charset, is a set of rules for turning text into bytes and back. UTF-8 is a common charset that can represent text from many languages.
The program that decodes the bytes must know which charset was used to encode them. If the charsets differ, the result may be wrong even if no error appears.
A UTF-8 round trip
This program encodes "café" as UTF-8 bytes, then decodes those bytes back into a string. Save it as EncodeText.java.
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
class EncodeText {
public static void main(String[] args) {
String text = "café";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String decoded = new String(bytes, StandardCharsets.UTF_8);
System.out.println(Arrays.toString(bytes));
System.out.println(decoded);
System.out.println(text.equals(decoded));
}
}Run these commands in the folder containing the file. The -encoding UTF-8 option tells the Java compiler how to read the source file.
javac -encoding UTF-8 EncodeText.java
java EncodeTextThe output is:
[99, 97, 102, -61, -87]
café
trueHere is what happens:
StandardCharsets.UTF_8names Java’s built-in UTF-8 charset. Theimportline makes that name available to the program.getBytesis a method, an action you can call on a string. It encodestextand returns a byte array. An array holds a sequence of values.new Stringcreates a string by decoding the array with UTF-8.Arrays.toString(bytes)makes the byte values readable for printing.equalschecks that the decoded text has the same contents as the original.
The text has four characters, but its UTF-8 form has five bytes. The first three letters each use one byte. é uses two. Java displays those last two bytes as negative numbers because its byte type uses signed values. The bytes are not damaged.
Keep the charset consistent
Use the same charset at both ends of a transfer. For example, if you save UTF-8 bytes to a file, read them as UTF-8 later. If another program sends the bytes, check which charset it uses.
Do not rely on the default charset when the data format calls for a particular one. Defaults can depend on the Java version or environment. Naming UTF-8 makes the choice clear.
Exercise
If you encode a string with UTF-8, which charset should you use to decode the resulting bytes? Why?
Show answer
Use UTF-8. It applies the same rules in reverse, so undamaged bytes can recover the original text.