Always use Encoding when converting bytes to Java Strings and vice versa

Going through some code, I see hundreds of places where people use string.getBytes() methods:

idBuilder.toString().getBytes()
payload.getBytes()
eventPayload.getBytes().length
etc

This is such a common mistake that internet is full of simple explanations of why you need to specify encoding. I copied this one from StackOverflow:

When text is stored in files or sent between computers over a socket, the text characters are stored or sent as a sequence of bits, almost always grouped in 8-bit bytes. The characters all have defined numeric values in Unicode, so that ‘A’ always has the value 0x41 (well, there are actually two other A’s in the Unicode character set, in the Greek and Russian alphabets, but that’s not relevant). But there are many mechanisms for how those numeric codes are translated to a sequence of bits when storing in a file or sending to another computer. In UTF-8, 0x41 is represented as 8 bits (the byte 0x41), but other numeric values (code points) will be converted to 16 or more bits with an algorithm that rearranges the bits; in UTF-16, 0x41 is represented as 16 bits; and there are other encodings like JIS and some which are capable of representing some but not all of the Unicode characters. Since String.getBytes() was intended to return a byte array that contains the bytes to be sent to a file or socket, the method needs to know what encoding it’s supposed to use when creating those bytes. Basically the encoding will have to be the same one that a program later reading a file, or a computer at the other end of the socket, expects it to be.

In fact, we had a build check at one of my previous companies that would FAIL the build when string.getBytes() is found in the source code.

Simple rule is:

NEVER ever rely on “default” encoding which would be used if you didn’t provide it. This encoding can be different on different machines.

Instead, use

import static java.nio.charset.StandardCharsets.UTF_8;
myString.getBytes(UTF_8);