The method getBytes() encodes a String into a byte array using the platform's default charset if no argument is passed.

We can pass a specific Charset to be used in the encoding process, either as a String object or a String object.

Available Signatures

public byte[] getBytes()
public byte[] getBytes(Charset charset)
public byte[] getBytes(String charsetName)


public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException {
    byte[] byteArray1 = "abcd".getBytes();
    byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII);
    byte[] byteArray3 = "ijkl".getBytes("UTF-8");
    byte[] expected1 = new byte[] { 97, 98, 99, 100 };
    byte[] expected2 = new byte[] { 101, 102, 103, 104 };
    byte[] expected3 = new byte[] { 105, 106, 107, 108 };
    assertArrayEquals(expected1, byteArray1);
    assertArrayEquals(expected2, byteArray2);
    assertArrayEquals(expected3, byteArray3);
Next »
Java String.indexOf()
« Previous
Java String.format()
November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:


Generic footer banner
Comments are closed on this article!