Java String getBytes() Method Example

There are four versions of getBytes()  methods. There is an alternative to getChars()  that stores the characters in an array of bytes.  
  • byte[] getBytes()  - Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
  • byte[] getBytes(Charset charset)  - Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
  • void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)  - Deprecated.
  • byte[] getBytes(String charsetName)  - Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

Java String getBytes() Method Example

Let's write an example to demonstrate all the getBytes() methods.
public class GetBytesExamples {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "javaguides";
         // Encodes this String into a sequence of bytes using the platform's
         // default charset, storing the result into a new byte array.
        byte[] bs = str.getBytes();
        for (byte b :  bs) {
            System.out.println(b);
        }
         // Encodes this String into a sequence of bytes using the given charset,
         // storing the result into a new byte array.
        byte[] bs1 = str.getBytes(Charset.forName("UTF-8"));
        for (byte b : bs1) {
            System.out.println(b);
        }
         // Encodes this String into a sequence of bytes using the given charset,
         // storing the result into a new byte array.
        byte[] bs2 = str.getBytes("UTF-8");
        for (byte b : bs2) {
            System.out.println(b);
        }
        byte[] dest = new byte[str.length()];
        str.getBytes(0, str.length(), dest, 0);
        for (byte b : dest) {
            System.out.println(b);
        }
    }
}
Output:
106
97
118
97
103
117
105
100
101
115
106
97
118
97
103
117
105
100
101
115
106
97
118
97
103
117
105
100
101
115
106
97
118
97
103
117
105
100
101
115



Comments