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()
Course – LS – All
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:


res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.