Languages
[Edit]
EN

Java - convert String to UTF-8 bytes

9 points
Created by:
Indira
499

In this short article we would like to show how to convert String to UTF-8 bytes in Java.

Quick solution:

// import java.nio.charset.StandardCharsets;

String text = "Hi, there!";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

Practical examples

1. Conversion with predefined property

Java 1.7 introduced StandardCharsets class with predefined properties.

package example;

import java.nio.charset.StandardCharsets;

public class Program {

    public static void main(String[] args) {

        String text = "Hi, there!";
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

        printBytes(bytes); // 72 105 44 32 116 104 101 114 101 33
    }

    private static void printBytes(byte[] data) {
        for (int i = 0; i < data.length; ++i) {
            if (i > 0) {
                System.out.print(" ");
            }
            System.out.print(data[i]);
        }
    }
}

2. Conversion with charset name

Using charset name we are able to make String conversion too. 

package example;

import java.io.UnsupportedEncodingException;

public class Program {

    public static void main(String[] args) throws UnsupportedEncodingException {

        String text = "Hi, there!";
        byte[] bytes = text.getBytes("utf8");

        printBytes(bytes); // 72 105 44 32 116 104 101 114 101 33
    }

    private static void printBytes(byte[] data) {
        for (int i = 0; i < data.length; ++i) {
            if (i > 0) {
                System.out.print(" ");
            }
            System.out.print(data[i]);
        }
    }
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join