Convert String to Byte Array in Java Using getBytes(Charset) 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 getBytes(Charset) method. This method converts the given string to a sequence of bytes using the given charset and returns an array of bytes. It is a predefined function of string class. Here, in this method we use an instance of Charset class, this class provides a named mapping between a sequence of the chars and a sequence of bytes. There are many charset defined and are discussed below.
- US-ASCII: Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
- ISO-8859-1: ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
- UTF-8: Eight-bit UCS Transformation Format
- UTF-16BE: Sixteen-bit UCS Transformation Format, big-endian byte order
- UTF-16LE: Sixteen-bit UCS Transformation Format, little-endian byte order
- UTF-16: Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark.
Syntax:
public byte[] getBytes(Charset charset)
Parameter: This function takes one argument, that is the charset which is used to encode the string
Return type: This function returns the resulting byte array.
Note:
- This method always replaces malformed input and unmappable character sequence with its charset’s default replacement byte array.
- If the given charset is not a valid charset, then this method will throw UnsupportedEncodingException.
- The length of the byte array is not the same as the given string, it depends upon the character encoding.
Let us discuss how to convert a string into a byte array with the help of the given examples:
Example 1:
Java
import java.io.*;
class GFG{
public static void main (String[] args)
{
String ss = "Hello GeeksforGeeks" ;
System.out.println( "String: " + ss);
try
{
byte [] res = ss.getBytes( "UTF-16" );
System.out.println( "Result : " );
for ( int i = 0 ; i < res.length; i++)
{
System.out.print(res[i]);
}
}
catch (UnsupportedEncodingException g)
{
System.out.println( "Unsupported character set" + g);
}
}
}
|
Output
String: Hello GeeksforGeeks
Result :
-2-1072010101080108011103207101010101010701150102011101140710101010101070115
Example 2:
Java
import java.io.*;
import java.util.Arrays;
class GFG{
public static void main (String[] args)
{
String ss = "Hello GFG" ;
System.out.println( "String: " + ss);
try
{
byte [] res = ss.getBytes( "US-ASCII" );
System.out.println( "Byte Array:" + Arrays.toString(res));
}
catch (UnsupportedEncodingException g)
{
System.out.println( "Unsupported character set" + g);
}
}
}
|
Output
String: Hello GFG
Byte Array:[72, 101, 108, 108, 111, 32, 71, 70, 71]
Last Updated :
28 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...