In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getByte() method. It is the easiest way to convert a string to a byte array. This method converts the given string to a sequence of bytes using the platform’s default charset and returns an array of bytes. It is a predefined function of string class. But it is an error-prone method and can return an erroneous result if the platform character encoding doesn’t match with the expected encoding.
public byte getBytes()
- In this method, the platform’s default encoding is used to convert the given string to the byte array if you do not specify any character encoding in the method.
- The length of the byte array is not the same as the given string, it depends upon the character encoding.
String: Hello GeeksforGeeks Byte Array: 72101108108111327110110110711510211111471101101107115
String: GeeksforGeeks Byte Array:[71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.