I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

This article is part of a series:
• Java String.String()
• Java String.getBytes()
• Java String.codePointCount()
• Java String.codePointAt()
• Java String.concat()
• Java String.contains()
• Java String.copyValueOf()
• Java String.endsWith()
• Java String.format()
• Java String.getBytes()
• Java String.indexOf()
• Java String.intern()
• Java String.isEmpty()
• Java String.lastIndexOf()
• Java String.regionMatches()
• Java String.replace()
• Java String.replaceAll()
• Java String.split()
• Java String.startsWith()
• Java String.subSequence()
• Java String.substring()
• Java String.toLowerCase()
• Java String.toUpperCase()
• Java String.trim()
• Java String.valueOf()

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)

Example

@Test
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);
}

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS