How to convert Java String into byte[]?
To convert a Java string into a byte array, you can use the getBytes()
method of the java.lang.String
class. This method returns an array of bytes representing the string in a specific encoding.
Here is an example of how you can use the getBytes()
method to convert a string into a byte array:
public class StringToByteArrayExample {
public static void main(String[] args) {
String str = "Hello World";
byte[] bytes = str.getBytes();
for (byte b : bytes) {
System.out.print(b + " ");
}
System.out.println();
}
}
This example converts the string "Hello World" into a byte array, and then prints the elements of the array. The output will be a series of bytes representing the string in the default encoding of the system.
By default, the getBytes()
method uses the default character encoding of the system to convert the string into a byte array. If you want to use a specific character encoding, you can pass the name of the encoding as a parameter to the getBytes()
method.
For example, to convert a string into a byte array using the UTF-8 encoding, you can do the following:
public class StringToByteArrayExample {
public static void main(String[] args) {
String str = "Hello World";
byte[] bytes = str.getBytes("UTF-8");
for (byte b : bytes) {
System.out.print(b + " ");
}
System.out.println();
}
}
This example uses the getBytes()
method with the "UTF-8" encoding to convert the string into a byte array. The resulting byte array will contain the bytes representing the string in the UTF-8 encoding.