Question

How to Convert a UTF-8 byte[] to a String in Java

csharp.netarraysstringtype-conversion

Question

I have a byte[] loaded from a file, and I know that the file content is encoded as UTF-8.

In some debugging code, I need to convert that byte array into a String. Is there a one-line way to do this in Java?

For example, given something like this:

byte[] data = ...; // loaded from a UTF-8 file

how can I convert it into a String correctly?

I assume this should mainly involve creating a new String from the bytes using the UTF-8 character encoding.

Short Answer

By the end of this page, you will understand how to convert a UTF-8 byte[] into a Java String, why character encodings matter, which APIs to use, and what mistakes to avoid when working with text loaded from files or network data.

Concept

Text in memory and text in files are not always stored the same way.

A Java String stores characters, while a byte[] stores raw bytes. To turn bytes into readable text, Java must know which character encoding was used when those bytes were created.

If your byte array is UTF-8 encoded, you should decode it as UTF-8:

String text = new String(bytes, StandardCharsets.UTF_8);

This matters because the same byte values can mean different characters under different encodings. If you use the wrong encoding, the result may contain garbled text like é instead of é.

UTF-8 is the most common encoding for files, APIs, JSON, logs, and web content, so knowing how to decode UTF-8 correctly is a basic and important Java skill.

In Java, the most direct way to convert a UTF-8 byte[] to a String is to use a String constructor that accepts both the byte array and the charset.

String text = new String(bytes, StandardCharsets.UTF_8);

This is clear, safe, and avoids relying on the platform default encoding.

Mental Model

Think of a byte[] as a box of numbered codes and a String as the final readable message.

The encoding is the dictionary used to translate those numbers into characters.

  • byte[] = raw encoded data
  • UTF-8 = the translation dictionary
  • String = the decoded human-readable text

If you use the wrong dictionary, the message is decoded incorrectly. So the key idea is simple:

Bytes are not text until you decode them with the correct charset.

Take Quiz

Syntax and Examples

The standard Java syntax is:

String text = new String(bytes, StandardCharsets.UTF_8);

You need this import:

import java.nio.charset.StandardCharsets;

Example

import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        byte[] bytes = {72, 101, 108, 108, 111};
        String text = new String(bytes, StandardCharsets.UTF_8);
        System.out.println(text);
    }
}

Output:

Hello

Example with non-ASCII characters

import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        byte[] bytes = "café".getBytes(StandardCharsets.UTF_8);
        String text = new String(bytes, StandardCharsets.UTF_8);
        System.out.println(text);
    }
}

Output:

café

This works correctly because the bytes were encoded as UTF-8 and then decoded using the same encoding.

Step by Step Execution

Consider this example:

import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        byte[] bytes = "Hi".getBytes(StandardCharsets.UTF_8);
        String text = new String(bytes, StandardCharsets.UTF_8);
        System.out.println(text);
    }
}

Step by step:

  1. "Hi".getBytes(StandardCharsets.UTF_8) converts the string Hi into UTF-8 bytes.
  2. Those bytes are stored in bytes.
  3. new String(bytes, StandardCharsets.UTF_8) tells Java to decode the byte array using UTF-8.
  4. Java reads the bytes and converts them back into characters.
  5. System.out.println(text) prints Hi.

For simple ASCII text like Hi, UTF-8 uses one byte per character. For characters like é, UTF-8 may use multiple bytes, which is why the charset must be specified explicitly.

Real World Use Cases

Converting byte[] to String with UTF-8 is common in many real programs:

  • Reading file contents: when a file is loaded as bytes and you want readable text
  • HTTP responses: APIs often return UTF-8 encoded JSON or plain text
  • Logging and debugging: inspect binary payloads that actually contain text
  • Message queues: systems often send UTF-8 encoded messages as bytes
  • Database exports/imports: text may be read from streams as raw bytes first
  • Configuration files: YAML, JSON, .properties, and text-based formats are often UTF-8

Example with a file:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

byte[] bytes = Files.readAllBytes(Path.of("data.txt"));
String text = new String(bytes, StandardCharsets.UTF_8);

Example with an API response body stored as bytes:

String json = new String(responseBytes, StandardCharsets.UTF_8);
Take Quiz

Real Codebase Usage

In real projects, developers often use this conversion in small, focused places rather than everywhere.

Common patterns

  • Debugging raw payloads
  • Validation before parsing
  • Reading text from files or streams
  • Converting request/response bodies
  • Guarding against null or empty data

Example with a guard clause

import java.nio.charset.StandardCharsets;

public String decodeBody(byte[] body) {
    if (body == null || body.length == 0) {
        return "";
    }
    return new String(body, StandardCharsets.UTF_8);
}

Example before JSON parsing

String json = new String(bytes, StandardCharsets.UTF_8);
if (!json.trim().startsWith("{")) {
    throw new IllegalArgumentException("Expected JSON object");
}

Why StandardCharsets.UTF_8 is preferred

In production code, developers usually prefer:

new String(bytes, StandardCharsets.UTF_8)

over:

new String(bytes, "UTF-8")

because it is:

  • type-safe
  • easier to read
  • free from checked exceptions
  • less error-prone than hardcoded charset names

Common Mistakes

A few common mistakes cause confusing bugs.

1. Using the platform default encoding

Broken example:

String text = new String(bytes);

Why this is a problem:

  • It uses the system default charset.
  • The result may differ between machines.
  • UTF-8 data can be decoded incorrectly on systems using a different default charset.

Use this instead:

String text = new String(bytes, StandardCharsets.UTF_8);

2. Encoding and decoding with different charsets

Broken example:

byte[] bytes = "café".getBytes(StandardCharsets.UTF_8);
String text = new String(bytes, java.nio.charset.StandardCharsets.ISO_8859_1);
System.out.println(text);

This produces incorrect text because the bytes were encoded as UTF-8 but decoded as ISO-8859-1.

3. Assuming bytes are always text

Not every byte[] represents text. Some byte arrays are:

  • images
  • compressed data
  • encrypted payloads
  • serialized binary formats

Trying to decode binary data as UTF-8 may produce nonsense or replacement characters.

4. Using old-style charset strings when not needed

Less ideal:

String text = new String(bytes, "UTF-8");

This can work, but modern Java code usually prefers:

String text = new String(bytes, StandardCharsets.UTF_8);

5. Forgetting partial data issues

If bytes come from a stream, make sure you have read the complete text before decoding. Decoding incomplete multibyte UTF-8 sequences can lead to broken characters.

Comparisons

Here is a quick comparison of common approaches:

ApproachExampleGood choice?Notes
Explicit UTF-8 decodingnew String(bytes, StandardCharsets.UTF_8)YesBest general choice for known UTF-8 data
Charset name as stringnew String(bytes, "UTF-8")UsuallyWorks, but less modern and less convenient
Default charsetnew String(bytes)NoDepends on machine settings
Read text directly from file APIFiles.readString(path, StandardCharsets.UTF_8)YesBest if you are reading from a file and do not need raw bytes

byte[] vs String

TypeStoresUse when
byte[]Raw binary dataWorking with files, network payloads, or encoded text
StringDecoded charactersDisplaying, parsing, searching, logging, or manipulating text

StandardCharsets.UTF_8 vs "UTF-8"

OptionRecommended?Reason
StandardCharsets.UTF_8YesSafer and cleaner
"UTF-8"AcceptableOlder style, can be more awkward in code
Take Quiz

Cheat Sheet

import java.nio.charset.StandardCharsets;

String text = new String(bytes, StandardCharsets.UTF_8);

Rules

  • Use the correct charset when converting bytes to text.
  • If the bytes are UTF-8, decode with StandardCharsets.UTF_8.
  • Avoid new String(bytes) unless you intentionally want the default charset.
  • Prefer StandardCharsets.UTF_8 over the string literal "UTF-8".

Common file shortcut

String text = java.nio.file.Files.readString(path, StandardCharsets.UTF_8);

Common reverse operation

byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

Warning signs

  • Text looks like é instead of é
  • Output changes across systems
  • Replacement character � appears

These usually mean the wrong charset was used.

FAQ

How do I convert a UTF-8 byte[] to a String in Java?

Use:

String text = new String(bytes, StandardCharsets.UTF_8);

Why should I not use new String(bytes)?

Because it uses the platform default charset, which may not be UTF-8 on every machine.

Is "UTF-8" the same as StandardCharsets.UTF_8?

They refer to the same encoding, but StandardCharsets.UTF_8 is usually preferred because it is safer and cleaner.

What happens if I use the wrong encoding?

The text may become corrupted or display strange characters such as ñ, é, or �.

Is converting bytes to a string always safe?

Only if the bytes actually represent text in the encoding you specify. Binary data should not be treated as text.

Can I read a UTF-8 file directly as a string instead of reading bytes first?

Yes. In many cases this is simpler:

String text = Files.readString(path, StandardCharsets.UTF_8);

Does UTF-8 always use one byte per character?

No. ASCII characters use one byte, but many other characters use two to four bytes.

Take Quiz

Mini Project

Description

Build a small Java utility that reads UTF-8 encoded bytes and prints the decoded text. This mirrors a common debugging task: inspecting file or network data that arrives as a byte[] but actually contains text.

Goal

Create a program that converts UTF-8 byte arrays into readable Java strings and demonstrates the result with sample inputs.

Requirements

  1. Create a byte[] from a sample UTF-8 string.
  2. Convert the byte array back into a String using UTF-8.
  3. Print both the byte length and the decoded text.
  4. Include at least one sample containing a non-ASCII character.
  5. Avoid using the platform default charset.
Take Quiz

Keep learning

Related questions

View more