The general information you come across is the fact that byte, generally byte [] is used in manipulating binary data, for example an image file, or while sending data over the network. I'll mention now, other use cases:
Encoding Strings in Java
In Java, the String object uses UTF-16, and the latter is immutable, i.e cannot be modified.
In order to encode strings, we convert them to UTF-8, which is compatible with ASCII. one way to do it, is to use java core, you can find out about more ways to go here.
To perform encoding, we copy the original string bytes to a byte array, and then create the desired one. Below, I'll give a simple example that shows why we need to encode strings, and how to do it:
- Why is encoding important?
Imagine you have this German word "Tschüss" and you're using US-ASCII:
String germanString = "Tschüss";
byte[] germanBytes = germanString.getBytes();
String asciiEncodedString = new String(germanBytes,StandardCharsets.US_ASCII);
assertNotEquals(asciiEncodedString, germanString);
and the output will simply be:
Tsch?ss
Because US_ASCII doesn't recognize the "ü".
Now here's the example that works:
String germanString = "Tschüss";
byte[] germanBytes = germanString.getBytes(StandardCharsets.UTF_8);
String utf8EncodedString = new String(germanBytes, StandardCharsets.UTF_8);
assertEquals(germanString, utf8EncodedString);
For the record, Java String is an Object that uses char arrays under the hood, including other data, you can find more in this answer.
Now imagine the case where you want to parse a huge amount of string data and using for instance split method. In this case, you'll have different objects (different char arrays) spread in different locations in the memory, which results in worse locality to the CPU, contrary to the case where you have a byte array since the beginning in one location. You can find out more in this interesting post this one.