The Java String getBytes Method encodes the String to the sequence of bytes using the user-specified charset, and it will store the result in the byte array.
Java String getBytes()
Java String getBytes() is a built-in method that helps us encode a given string into a byte code sequence and return an array of bytes. The getBytes() function encodes the StrStringto a sequence of bytes using the specified charset and returns the array of those bytes. In addition, it throws UnsupportedEncodingException – If the specified charset is not supported.
The getBytes() function can be implemented in two ways:
public byte[] getBytes(String charsetName)
The method encodes a string into a sequence of bytes using some specified charset and returns the array of those bytes. If the specified charset is not supported, it throws an exception called UnsupportedEncodingException.
See the following program of String getBytes().
import java.io.*; class GetBytes { public static void main(String args[]) { String str = "Welcome to Appdividend"; System.out.println("The String before conversion is : "); System.out.println(str); // converting the string into byte // using getBytes ( converts into ASCII values ) byte[] arr = str.getBytes(); // Displaying converted string after conversion System.out.println("The String after conversion is : "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); } System.out.println("\n"); } }
See the following output.
public byte[] getBytes()
It encodes the String to the default charset method. There is some default charset defined in Java; some of them are:
- 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.
See the following programing example of the getBytes() function.
import java.io.*; class GetBytes { public static void main(String args[]) { String str = new String("Welcome to Appdividend"); byte[] array1 = str.getBytes(); // Printing default charset encoding System.out.print("Default Charset encoding:"); for (byte b : array1) { System.out.print(b); } // printing UTF-16 Charset encoding System.out.print("\nUTF-16 Charset encoding:"); try { byte[] array2 = str.getBytes("UTF-16"); for (byte b1 : array2) { System.out.print(b1); } // converting UTF-16BE encoding byte[] array3 = str.getBytes("UTF-16BE"); System.out.print("\nUTF-16BE Charset encoding:"); for (byte b2 : array3) { System.out.print(b2); } System.out.println("\n"); // throwing exception } catch (UnsupportedEncodingException ex) { System.out.println("Unsupported character set" + ex); } } }
See the output.
That’s it for this tutorial.