# Convert String to UTF-8 bytes in Java

Java 8Object Oriented ProgrammingProgramming

Before converting a String to UTF-8-bytes, let us have a look at UTF-8.

UTF-8 is a variable width character encoding. UTF-8 has ability to be as condense as ASCII but can also contain any unicode characters with some increase in the size of the file. UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4.

In order to convert a String into UTF-8, we use the getBytes() method in Java. The getBytes() method encodes a String into a sequence of bytes and returns a byte array.

Declaration − The getBytes() method is declared as follows −

public byte[] getBytes(String charsetName)

where charsetName is the specific charset by which the String is encoded into an array of bytes.

Let us see a program to convert a String into UTF-8 bytes in Java.

## Example

Live Demo

public class Example {
public static void main(String args[]) throws Exception {
String s = "Hello World";
byte arr[] = s.getBytes("UTF8");
for (byte x: arr) {
System.out.print(x+" ");
}
}
}

## Output

72 101 108 108 111 32 87 111 114 108 100

Let us understand the above program. We have created a String s −

String s = "Hello World";

String s is assigned the value Hello World.

To convert it into UTF-8, we use the getBytes(“UTF-8”) method. This gives us an array of bytes as follows −

byte[] arr = s.getBytes("UTF-8");

Then to print the byte array, we use an enhanced for loop as follows −

for (byte x: arr) {
System.out.print(x+" ");
}
{"ft_lang_label":"__label__en","ft_lang_prob":0.7879594,"math_prob":0.72396,"size":1506,"snap":"2020-45-2020-50","text_gpt3_token_len":377,"char_repetition_ratio":0.12849534,"word_repetition_ratio":0.053030305,"special_character_ratio":0.27888447,"punctuation_ratio":0.10197368,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95072436,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-30T11:38:44Z\",\"WARC-Record-ID\":\"<urn:uuid:938a5fa3-96b4-4758-99af-876ea9fec052>\",\"Content-Length\":\"28208\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:bd01b01e-d80c-477c-ab3e-14e816a62911>\",\"WARC-Concurrent-To\":\"<urn:uuid:4df98b04-2949-4876-8270-5f33e96efe4e>\",\"WARC-IP-Address\":\"72.21.91.42\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/convert-string-to-utf-8-bytes-in-java\",\"WARC-Payload-Digest\":\"sha1:RXGR5RWOMHE4SBHMW54MZYAT6UJYZPMM\",\"WARC-Block-Digest\":\"sha1:Y23SK7HGQWNZMZWT5QRE5ESG7OI7FICY\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107910204.90_warc_CC-MAIN-20201030093118-20201030123118-00531.warc.gz\"}"}