English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String getBytes() method encodes the string into a byte sequence and stores it in a byte array.
The syntax of the String getBytes() method is:
string.getBytes() string.getBytes(Charset charset) string.getBytes(String charsetName)
The getBytes() method returns a byte array.
If no parameters are passed, getBytes() uses the platform's default character set to encode the string.
import java.util.Arrays; class Main {}} public static void main(String[] args) { String str = "Java"; byte[] byteArray; //Convert the string to a byte array //Using the platform's default character set byteArray = str.getBytes(); System.out.println(Arrays.toString(byteArray)); } }
Output Result
[74, 97, 118, 97]
Note:In the above example, we used the Arrays class to print the byte array in a readable form. It is unrelated to getBytes().
These are other methods available in CharsetJava:
UTF-8 - 8-bit UCS transformation format
UTF-16 - 16-bit UCS transformation format
UTF-16BE - 16-bit UCS transformation format, big-endian byte order
UTF-16LE - 16-bit UCS transformation format, little-endian byte order
US-ASCII - 7-bit ASCII
ISO-8859-1 - ISO Latin alphabet1Number
import java.util.Arrays; import java.nio.charset.Charset; class Main {}} public static void main(String[] args) { String str = "Java"; byte[] byteArray; //Using UTF-8Encoding byteArray = str.getBytes(Charset.forName("UTF"-8")); System.out.println(Arrays.toString(byteArray)); //Using UTF-16Encoding byteArray = str.getBytes(Charset.forName("UTF"-16")); System.out.println(Arrays.toString(byteArray)); } }
Output Result
[74, 97, 118, 97] [-2, -1, 0, 74, 0, 97, 0, 118, 0, 97]
Note:In the above program, we imported java.nio.charset.Charset to use Charset. And, we have imported the Arrays class to print the byte array in a readable form.
You can also use a string to specify the encoding type of getBytes(). When used in this way, the code must be wrapped inWithin the try ... catch block.
import java.util.Arrays; class Main {}} public static void main(String[] args) { String str = "Java"; byte[] byteArray; try { byteArray = str.getBytes("UTF-8"); System.out.println(Arrays.toString(byteArray)); byteArray = str.getBytes("UTF-16"); System.out.println(Arrays.toString(byteArray)); //Incorrect Encoding //Throw Exception byteArray = str.getBytes("UTF-34"); System.out.println(Arrays.toString(byteArray)); }) catch (Exception e) { System.out.println(e + "encoding is wrong"); } } }
Output Result
[74, 97, 118, 97] [-2, -1, 0, 74, 0, 97, 0, 118, 0, 97] java.io.UnsupportedEncodingException: UTF-34 encoding is wrong
Note:We have imported java.util.Arrays to print the byte array in a readable format. It is unrelated to getBytes().