Java Program to Convert String to Byte Array Using getBytes() Method
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.
Syntax:
public byte[] getBytes()
Note:
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.
Example 1:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String ss = "Hello GeeksforGeeks";
System.out.println("String: " + ss);
byte[] res = ss.getBytes();
System.out.println("Byte Array:");
for (int i = 0; i < res.length; i++) {
System.out.print(res[i]);
}
}
}
Output
String: Hello GeeksforGeeks
Byte Array:
72101108108111327110110110711510211111471101101107115
Example 2:
Java
import java.io.*;
import java.util.Arrays;
class GFG {
public static void main(String[] args)
{
String ss = "GeeksforGeeks";
System.out.println("String: " + ss);
byte[] res = ss.getBytes();
System.out.println("Byte Array:"
+ Arrays.toString(res));
}
}
Output
String: GeeksforGeeks
Byte Array:[71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]
Last Updated :
19 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...