There is simpler approach to decode a ByteBuffer into a String without any problems, mentioned by Andy Thomas.

String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
Answer from xinyong Cheng on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › convert-a-string-to-a-bytebuffer-in-java
Convert a String to a ByteBuffer in Java - GeeksforGeeks
January 31, 2024 - In example 1 we print the original string value as well as ByteBuffer content only, but in this example, we print every byte in the buffer, but it is in the form of decimal only. And same steps follow what we follow in Example 1. ... // Java Program to Convert String to ByteBuffer import java.nio.ByteBuffer; import java.nio.charset.Charset; // Driver Class public class StringToByteBufferExampleTwo { // main function public static void main(String[] args) { // Step 1: Create a String String inputString = "Welcome to GeeksForGeeks"; // Step 2: Choose a character encoding (e.g., UTF-8) Charset ch
Discussions

ByteBuffer to String
The String constructor can take a byte array as its initializer. By default it uses the platform-default character encoding which is usually ISO-8859-1. That is fine for simple ASCII stuff but for a "real" system that might talk in multiple languages and what not usually a form of UTF is desired for normalization of data. This stuff matters because bytes have no meaning in and of themselves. Converting them to Strings means interpreting them a certain way. UTF for example might take 4 bytes to make one specific character in its set whereas in ASCII that would probably be interpreted as 4 characters of gibberish. More on reddit.com
🌐 r/java
3
0
April 9, 2013
ByteBuffer to String in Java - Stack Overflow
Btw. new String(byte[]) internally uses a CharSet decoder on a ByteBuffer wrapped around your input byte array. ... Sign up to request clarification or add additional context in comments. ... Java's String class is immutable. In order to maintain this guarantee, String has to have its own reference ... More on stackoverflow.com
🌐 stackoverflow.com
April 5, 2017
arrays - Converting a String to ByteBuffer in Java - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. More on stackoverflow.com
🌐 stackoverflow.com
July 18, 2020
java - Put a StringBuffer in a ByteBuffer - Stack Overflow
I am trying to put a string buffer in a bytebuffer.. out.put(ss); where out is a ByteBuffer and ss is a StringBuffer. Is there any easy way to do this? Assuming ASCII encoding for the string. Thanks More on stackoverflow.com
🌐 stackoverflow.com
September 22, 2016
Top answer
1 of 3
56

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

2 of 3
55

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

🌐
Blogger
self-learning-java-tutorial.blogspot.com › 2021 › 12 › java-convert-string-to-bytebuffer.html
Programming for beginners: Java: Convert string to ByteBuffer
December 13, 2021 - package com.sample.app.strings; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; public class StringToByteBuffer { public static void main(String args[]) { ByteBuffer byteBuffer = ByteBuffer.allocate(100); byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8)); byteBuffer.flip(); String str = StandardCharsets.UTF_8.decode(byteBuffer).toString(); System.out.println("str : " + str); } }
🌐
Baeldung
baeldung.com › home › java › java string › convert a bytebuffer to string in java
Convert a ByteBuffer to String in Java | Baeldung
August 15, 2025 - ByteBuffer is one of many beneficial classes in the java.nio package. It’s used to read data from channels and write data into channels directly. In this short tutorial, we’ll learn how to convert a ByteBuffer to String in Java.
🌐
GitHub
gist.github.com › qingniufly › 9d976136d908f1e52a1b69b40449565b
Java NIO, ByteBuffer <--> String - Gist - GitHub
Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop. Download ZIP · Java NIO, ByteBuffer <--> String · Raw · ByteBufferConverter.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
javathinking
javathinking.com › blog › convert-string-to-bytebuffer-java
Converting String to ByteBuffer in Java — javathinking.com
In this example, we first convert the String to a byte array using the UTF - 8 encoding. Then, we allocate a ByteBuffer with the same capacity as the byte array and put the bytes into the buffer.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 371961 › java › String-byte-buffer
String into byte buffer (Java in General forum at Coderanch)
October 12, 2003 - Previously you were asking about ByteBuffer and CharBuffer. (Capitalization is important in Java.) You can convert a String to a CharBuffer using CharBuffer.wrap(CharSequence) (note that a String is also a CharSequence) and then you can use a CharsetEncoder to convert the CharBuffer to a ByteBuffer.
🌐
Reddit
reddit.com › r/java › bytebuffer to string
r/java on Reddit: ByteBuffer to String
April 9, 2013 -

Hi Guys,

Could anyone please tell me how I can convert a ByteBuffer to a String? I thought it would be a simple function but I can't seem to work it out.

This is just a part of what I have written. I am essentially trying to read a message sent via TCP. There were intermediate steps which I didn't think were necessary to include here.

ServerSocketChannel tcpserver = ServerSocketChannel.open();
SocketChannel connectionSocket = tcpserver.accept();

// create buffer to hold message
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = connectionSocket.read(buf);

While googling around, there was talk of paying attention to character encoding. Could someone please explain how this factors into the problem at hand?

Any help would be greatly appreciated!!

Kind Regards,

Giri

🌐
GitHub
gist.github.com › 9d976136d908f1e52a1b69b40449565b
Java NIO, ByteBuffer <--> String · GitHub
Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop. Download ZIP · Java NIO, ByteBuffer <--> String · Raw · ByteBufferConverter.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
Top answer
1 of 2
7

A way to convert a ByteBuffer to a String would be to use a Charset to decode the bytes:

Charset charset = Charset.forName("ISO-8859-1");

ByteBuffer m_buffer = ...;

String text = charset.decode(m_buffer).toString();

The decoding creates a CharBuffer which you can conveniently convert to a String. You can reuse the CharSet and it is threadsafe. I wouldn't worry too much about performance (re "fastest way") unless you have really a problem in that area. A general advice, when you want to use ByteBuffer, do the to-String conversion as late as possible, and only when the String is needed.

As 14jbella mentioned, Strings are immutable. There is no way of creating a String from an array (char or byte) that does not include copying the data because arrays are mutable. So no, there is no way to do it without copying.

Further you should take into consideration, that m_buffer.array() returns the internal array of the ByteBuffer, which may be much more than the actual data stored in the buffer. Creating a String from that array might lead to a potentially huge memory allocation, because the data gets copied into a new array. For example if you're using a 256 MB ByteBuffer somewhere in your code, and you get a slice() of 32 bytes named m_buffer from that buffer to convert to a String, your invocation of new String(m_buffer.array()) would allocate a new byte array of the size of the original, backing byte array, which is 256 MB, which is probably not that fast, if it requires a GC.

Btw. new String(byte[]) internally uses a CharSet decoder on a ByteBuffer wrapped around your input byte array.

2 of 2
4

Java's String class is immutable. In order to maintain this guarantee, String has to have its own reference to the char[] backing it, and nobody else may have that reference. If it were to share an array with the ByteBuffer, the String class could not guarantee that it would not be modified. In addition, char, and byte are not the same in Java.

🌐
Blogger
psy-lob-saw.blogspot.com › 2012 › 12 › encode-utf-8-string-to-bytebuffer-faster.html
Psychosomatic, Lobotomy, Saw: Encode UTF-8 String to a ByteBuffer - faster
Summary: By utilizing Unsafe to gain access to String/CharBuffer/ByteBuffer internals and writing a specialized UTF-8 encoder we can get a significant(> 30%) performance gain over traditional methods and maintain that advantage for both heap and direct buffers across different JDK versions.
Top answer
1 of 1
4

getBytes uses the platforms default charset, not necessarily ASCII.

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

StandardCharsets.US_ASCII.encode actually uses ASCII.

If you use str.getBytes(StandardCharsets.US_ASCII), however, then they will be do the same thing on a high level.

After a quick look into their implementations, getBytes seems to do a very different thing from encode, so to find out which one is quicker in terms of performance, you'd have to do a benchmark.

EDIT:

I wrote a JMH benchmark:

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 10)
@Fork(value = 1)
public class Main {

    static final String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    public static void main (String args[]) throws IOException, RunnerException {
        org.openjdk.jmh.Main.main(args);
    }

    @Benchmark
    public void wrap(Blackhole bh) {

        bh.consume(ByteBuffer.wrap(s.getBytes(StandardCharsets.US_ASCII)));
    }

    @Benchmark
    public void encode(Blackhole bh) {
        bh.consume(StandardCharsets.US_ASCII.encode(s));
    }
}

This is the result:

Benchmark    Mode  Cnt     Score    Error  Units
Main.encode  avgt   20  2407.242 ± 28.147  ns/op
Main.wrap    avgt   20   199.227 ±  4.093  ns/op

So wrap is a lot faster.

🌐
DigitalOcean
digitalocean.com › community › tutorials › string-byte-array-java
String to byte array, byte array to String in Java | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Java67
java67.com › 2015 › 06 › how-to-convert-bytebuffer-to-string-in-java-example.html
How to convert ByteBuffer to String in Java [Example] | Java67
In this Java program, I have first created a String literal, then I have got the byte array from that String in the UTF-8 encoding scheme. After that, I have created a ByteBuffer object by using the same byte array and using ByteBuffer.wrap() method.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio › bytebuffer
Use ByteBuffer to store Strings - Java Code Geeks
March 19, 2019 - Allocate a new ByteBuffer and set ... method so as to be able to put characters directly into the byte buffer · Using the put(String) API method we can put a String directly to the byte buffer...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › ByteBuffer.html
ByteBuffer (Java Platform SE 8 )
July 21, 2026 - Reads eight bytes at the given index, composing them into a long value according to the current byte order. ... IndexOutOfBoundsException - If index is negative or not smaller than the buffer's limit, minus seven · public abstract ByteBuffer putLong(int index, long value)