I need String of size got

You can use String constructor String(char[] value,int offset,int count)

String s = new String(buf,0,got);

Sample code:

char buf[] = new char[4096];
buf[0]='a';
buf[1]='b';
buf[2]='c';
int got = 2;
String s = new String(buf,0,got);
System.out.println(s);      // ab
Answer from Braj on Stack Overflow
🌐
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 - We will use a simple example to showcase all the three ways of converting a ByteBuffer to a String. The first step is to get the byte array from ByteBuffer. To do that, we’ll call the ByteBuffer.array() method. This will return the backing array. Then, we can call the String constructor, which accepts a byte array and character encoding to create our new String:
Discussions

Java ByteBuffer to String - Stack Overflow
More frequently, you'll want to specify the encoding. However, there's a simpler way to do that than the question you linked. The String API provides methods that converts between a String and a byte[] array in a particular encoding. More on stackoverflow.com
🌐 stackoverflow.com
arrays - Convert ByteBuffer to String in Java - Stack Overflow
Then i get a java.nio.BufferUnderflowException and the string still doesn't make sense 2015-03-22T04:22:08.927Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
July 20, 2016
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
java - What is the difference in converting string buffer to string using .toString(), String.valueOf() and + " " - Stack Overflow
It's a command line tool that ships with the JDK. javap -v myclass.class 2014-08-07T06:14:58.373Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... You don’t understand DNS like you think you... Dispatches from O'Reilly: From capabilities to... More on stackoverflow.com
🌐 stackoverflow.com
🌐
BeginnersBook
beginnersbook.com › 2015 › 04 › convert-stringbuffer-to-string
Java – How to convert StringBuffer to String
The toString() method of StringBuffer class can be used to convert StringBuffer content to a String. This method returns a String object that represents the contents of StringBuffer.
🌐
Coderanch
coderanch.com › t › 388160 › java › Converting-String-StringBuffer
Converting from a String to a StringBuffer (Beginning Java forum at Coderanch)
String s = new String(stringBuffer); vice versa use toString(); D.J ... "Dean J", The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp .
🌐
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.
🌐
javathinking
javathinking.com › blog › convert-buffer-to-string-java
Convert Buffer to String in Java — javathinking.com
Capacity: The maximum number of elements the buffer can hold. Position: The index of the next element to be read or written. Limit: The index of the first element that should not be read or written. When converting a ByteBuffer to a string, encoding and decoding play a crucial role. Encoding is the process of converting characters to bytes, and decoding is the reverse process. Java provides the Charset class to handle different character encodings such as UTF - 8, ISO - 8859 - 1, etc.
Find elsewhere
Top answer
1 of 4
12

You need to use the buffer's position and limit to determine the number of bytes to read.

// ...populate the buffer...
buffer.flip(); // flip the buffer for reading
byte[] bytes = new byte[buffer.remaining()]; // create a byte array the length of the number of bytes written to the buffer
buffer.get(bytes); // read the bytes that were written
String packet = new String(bytes);

In my opinion you shouldn't really be using the backing array() at all; it's bad practice. Direct byte buffers (created by ByteBuffer.allocateDirect() won't have a backing array and will throw an exception when you try to call ByteBuffer.array(). Because of this, for portability you should try to stick to the standard buffer get and put methods. Of course, if you really want to use the array you can use ByteBuffer.hasArray() to check if the buffer has a backing array.

2 of 4
1

The answer talking about setting range from position to limit is not correct in a general case. When the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):

if (myByteBuffer.hasArray()) {
    return new String(myByteBuffer.array(),
        myByteBuffer.arrayOffset() + myByteBuffer.position(),
        myByteBuffer.remaining());
} else {
    final byte[] b = new byte[myByteBuffer.remaining()];
    myByteBuffer.duplicate().get(b);
    return new String(b);
}

For the concerns related to encoding, see Andy Thomas' answer.

🌐
Bun
bun.sh › binary data › convert a buffer to a string
Convert a Buffer to a string - Bun
August 4, 2026 - The Buffer class provides a .toString() method that converts a Buffer to a string.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › stringbuffer_tostring.htm
Java StringBuffer toString() Method
Python TechnologiesDatabasesComputer ... Tutorials View All Categories ... The Java StringBuffer toString() method is used to retrieve a string representing the data in a StringBuffer object....
🌐
Coderanch
coderanch.com › t › 385588 › java › convert-StringBuffer-String
How to convert StringBuffer to String ? (Java in General forum at Coderanch)
Try the following code: StringBuffer sbuf = new StringBuffer("sameer"); String str = sbuf.toString(); System.out.println(str); toString() will convert from StringBuffer to String object
🌐
Bun
bun.com › guides › binary data › buffer to string
Convert a Buffer to a string | Bun Guides
The Buffer class provides a .toString() method that converts a Buffer to a string.
🌐
Codemia
codemia.io › knowledge-hub › path › java_bytebuffer_to_string
Java ByteBuffer to String
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-tostring-method-in-java-with-examples
ByteBuffer toString() method in Java with Examples - GeeksforGeeks
August 6, 2021 - // Java program to demonstrate // toString() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // creating object of 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

🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › StringBuffer.html
StringBuffer (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
🌐
University of Texas
cs.utexas.edu › ~mitra › uil › Capital2014 › notes › strings.html
String and StringBuffer
Convert a String Buffer to a String · String str = strBuf4.toString(); You can pass parameters to the method main() from the command line. The command line parameters are stored in the String array args. Supposing you start the program as follows: java prog 1 2 3 The numbers 1, 2, and 3 will ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › StringBuffer.html
StringBuffer (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
Top answer
1 of 2
9

This

StringBuffer sb = new StringBuffer("Welcome");
String st = sb + "";

will result more or less in

StringBuffer sb = new StringBuffer("Welcome");
StringBuilder builder = new StringBuilder();
builder.append((sb == null) ? "null" : sb.toString());
builder.append("");
String st = builder.toString();
2 of 2
6

If we compile them into two methods in java

private StringBuffer sb = new StringBuffer("Welcome");

public String testToString() {
  return sb.toString();
}

public String testAppend() {
  return sb + "";
}

and then use javap -v, we get

public java.lang.String testToString();
  descriptor: ()Ljava/lang/String;
  flags: ACC_PUBLIC
  Code:
    stack=1, locals=1, args_size=1
       0: aload_0       
       1: getfield      #19                 // Field sb:Ljava/lang/StringBuffer;
       4: invokevirtual #27                 // Method java/lang/StringBuffer.toString:()Ljava/lang/String;
       7: areturn       
    LineNumberTable:
      line 10: 0
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0       8     0  this   Lcom/stackoverflow/Question;

public java.lang.String testAppend();
  descriptor: ()Ljava/lang/String;
  flags: ACC_PUBLIC
  Code:
    stack=2, locals=1, args_size=1
       0: new           #31                 // class java/lang/StringBuilder
       3: dup           
       4: invokespecial #33                 // Method java/lang/StringBuilder."<init>":()V
       7: aload_0       
       8: getfield      #19                 // Field sb:Ljava/lang/StringBuffer;
      11: invokevirtual #34                 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
      14: invokevirtual #38                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      17: areturn       
    LineNumberTable:
      line 14: 0
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0      18     0  this   Lcom/stackoverflow/Question;

So appending appears to be slightly less efficient as it uses an extra bit of stack and contains more instructions.