Just use

return ma.toString();

instead of

return ma;

ma.toString() returns the string representation for your StringBuilder.

See StringBuilder#toString() for details

As Valeri Atamaniouk suggested in comments, you should also return something in the catch block, otherwise you will get a compiler error for missing return statement, so editing

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
}

to

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
    return null; //or maybe return another string
}

Would be a good idea.


EDIT

As Esailija suggested, we have three anti-patterns in this code

} catch (Exception e) {           //You should catch the specific exception
    Log.e("ERR",e.getMessage());  //Don't log the exception, throw it and let the caller handle it
    return null;                  //Don't return null if it is unnecessary
}

So i think it is better to do something like that:

private static String getUrlSource(String url) throws MalformedURLException, IOException {
    URL localUrl = null;
    localUrl = new URL(url);
    URLConnection conn = localUrl.openConnection();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String line = "";
    String html;
    StringBuilder ma = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        ma.append(line);
    }
    return ma.toString();
}

And then, when you call it:

try {
    String urlSource = getUrlSource("http://www.google.com");
    //process your url source
} catch (MalformedURLException ex) {
    //your url is wrong, do some stuff here
} catch (IOException ex) {
    //I/O operations were interrupted, do some stuff here
}

Check these links for further details about Java Anti-Patterns:

  • Java Anti-Patterns
  • Programming Anti-Patterns
  • An Introduction to Antipatterns in Java Applications
Answer from BackSlash on Stack Overflow
Top answer
1 of 3
54

Just use

return ma.toString();

instead of

return ma;

ma.toString() returns the string representation for your StringBuilder.

See StringBuilder#toString() for details

As Valeri Atamaniouk suggested in comments, you should also return something in the catch block, otherwise you will get a compiler error for missing return statement, so editing

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
}

to

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
    return null; //or maybe return another string
}

Would be a good idea.


EDIT

As Esailija suggested, we have three anti-patterns in this code

} catch (Exception e) {           //You should catch the specific exception
    Log.e("ERR",e.getMessage());  //Don't log the exception, throw it and let the caller handle it
    return null;                  //Don't return null if it is unnecessary
}

So i think it is better to do something like that:

private static String getUrlSource(String url) throws MalformedURLException, IOException {
    URL localUrl = null;
    localUrl = new URL(url);
    URLConnection conn = localUrl.openConnection();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String line = "";
    String html;
    StringBuilder ma = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        ma.append(line);
    }
    return ma.toString();
}

And then, when you call it:

try {
    String urlSource = getUrlSource("http://www.google.com");
    //process your url source
} catch (MalformedURLException ex) {
    //your url is wrong, do some stuff here
} catch (IOException ex) {
    //I/O operations were interrupted, do some stuff here
}

Check these links for further details about Java Anti-Patterns:

  • Java Anti-Patterns
  • Programming Anti-Patterns
  • An Introduction to Antipatterns in Java Applications
2 of 3
3

I have same problem while converting StringBuilder to String, and i use above point but that's not give correct solution. using above code output comes like this

    String out=ma.toString();
// out=[Ljava.lang.String;@41e633e0

After that i find out correct solution.Think is create a new String instant inserted of StringBuilder like this..

String out=new String(ma);
Discussions

scala - What's the correct way to convert from StringBuilder to String? - Stack Overflow
From what I've seen online, people seem to suggest that the toString() method is to be used, however the documentation states: Creates a String representation of this object. The default representa... More on stackoverflow.com
🌐 stackoverflow.com
java - String cannot be converted to StringBuffer - Stack Overflow
You seem to be using a StringBuffer the way you would use a String, which isn't the point of a StringBuffer (or StringBuilder). ... @ajb what should I do? I researched that when you need to use insert, you have to use StringBuilder. So now I'm having the error of it no tbeing converted to String. More on stackoverflow.com
🌐 stackoverflow.com
c# - some problems with converting from StringBuilder to string - Stack Overflow
It adds \ before every ". What's the problem? ... you see the "\" in the debugger when you analyze the string? More on stackoverflow.com
🌐 stackoverflow.com
java - How can a StringBuilder best be converted to a String[]? - Stack Overflow
The following code sort of works, but fixes the number of elements in String[]. Is there a way to make a String[] add the number of elements needed dynamically? private static StringBuilder names ... More on stackoverflow.com
🌐 stackoverflow.com
August 12, 2010
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.stringbuilder.tostring
StringBuilder.ToString Method (System.Text) | Microsoft Learn
September 15, 2021 - You must call the ToString method to convert the StringBuilder object to a String object before you can pass the string represented by the StringBuilder object to a method that has a String parameter or display it in the user interface.
🌐
Google Sites
sites.google.com › site › sharingwithfrn › basics › java › string › string-builder
string builder - sharingwithfrn
public static void concat2(StringBuilder s2){ //StringBuilder s = "geeks"; //Error: incompatible types: String cannot be converted to StringBuilder //s2=s2+"forgeeks"; //Error: incompatible types: String cannot be converted to StringBuilder StringBuilder s = new StringBuilder("geeks"); //This ...
Top answer
1 of 2
6

The toString implementation currently just redirects to the result method anyway, so those two methods will behave in the same way. However, they express slightly different intent:

  • toString requests a textual representation of StringBuilders current state that is "concise but informative (and) that is easy for a person to read". So, theoretically, the (vague) specification of this method does not forbid abbreviating the result, or enhancing conciseness and readability in any other way.
  • result requests the actual constructed string. No different readings seem possible here.

Therefore, if you want to obtain the resulting string, use result to express your intent as clearly as possible.

In this way, the reader of your code won't have to wonder whether StringBuilder.toString might shorten something for the sake of "conciseness" when the string gets over 9000 kB long, or something like that.

The mkString is for something else entirely, it's mostly used for interspersing separators, as in "hello".mkString(",") == "h,e,l,l,o".

Some further links:

  • The paragraph with "hashcode in hexadecimal" describes the default. It is just documentation inherited from AnyRef, because the creator of StringBuilder didn't bother to provide more detailed documentation.
  • If you look into code, you'll see that toString is actually just delegating to result.
  • The documentation of StringBuilder also mentions result() in the introductory overview paragraph.

Just use result().

2 of 2
2

TL;DR; use result as stated in the docs.

toString MUST never be called in anything at all for another purpose other than a quick debug.

mkString is inherited from collections hierarchy and it will basically create another StringBuilder so is very inefficient.

🌐
Benchresources
benchresources.net › home › java › java – how to convert string to stringbuilder and vice-versa ?
Java - How to convert String to StringBuilder and vice-versa ? - BenchResources.Net
October 8, 2022 - In this article, we will discuss how to convert String to StringBuilder and vice-versa · Note: String to StringBuffer conversion is also possible, read StringBuffer to String conversion and vice-versa · String to StringBuilder using append() method · StringBuilder to String using toString() method · Let us move forward and discuss above conversions · public StringBuilder append(String str); package in.bench.resources.string.to.stringbuilder; public class ConvertStringIntoStringBuilderUsingAppendMethod { public static void main(String[] args) { // String - 1 String str1 = "This is Java Weblog.
🌐
GeeksforGeeks
geeksforgeeks.org › java › conversion-between-string-stringbuilder-and-stringbuffer
Conversion Between String, StringBuilder, and StringBuffer - GeeksforGeeks
February 20, 2026 - Explanation: The above example shows how to convert StringBuffer and StringBuilder objects into String with the help of toString() method. There is no direct conversion between StringBuffer and StringBuilder.
Find elsewhere
🌐
javathinking
javathinking.com › blog › convert-string-builder-to-string-java
Converting StringBuilder to String in Java — javathinking.com
StringBuilder provides methods like append(), insert(), delete(), etc., to modify the sequence of characters. The String class in Java represents an immutable sequence of characters. Once a String object is created, its value cannot be changed.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-convert-string-to-stringbuilder-and-vice-versa-java
How to convert String to StringBuilder and vice versa Java?
Java provides StringBuffer class as a replacement of Strings in places where there is a necessity to make a lot of modifications to Strings of characters. You can modify/manipulate the contents of a StringBuffer over and over again without leaving behind a lot of new unused objects. The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilder’s methods are not thread safe (not synchronized).
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.text.stringbuilder
StringBuilder Class (System.Text) | Microsoft Learn
The StringBuilder class lacks search methods such as IndexOf or StartsWith. You'll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder.
🌐
PC Review
pcreview.co.uk › newsgroups › microsoft dotnet › microsoft c# .net
How to convert from string to stringbuilder? | PC Review
November 25, 2004 - When having a string that is defined as a stringbuilder it can be converted to a string by this: StringbuilderText.ToString(); But what about the otherway...
🌐
Coderanch
coderanch.com › t › 787475 › java › Clarifying-Purpose-StringBuilder-toString-Method
Clarifying the Purpose of StringBuilder's toString() Method (Java in General forum at Coderanch)
January 23, 2025 - Hey there, I just wanted to clarify this StringBuilder Behaviour. But this happens fine The toString() method must be called on "StringBuilder" to convert it into a "String," as it does not return a String.
🌐
TutorialsPoint
tutorialspoint.com › converting-a-stringbuilder-to-string-in-java
Java StringBuilder toString() Method
September 2, 2023 - A string is a constant, which means that we cannot change the string value once it has been initialized. The toString() method does not accept any parameter, and it does not throw any exception while converting an object to a string.
🌐
CodeProject
codeproject.com › Questions › 1230186 › Stringbuilder-to-string-conversion-in-java
Stringbuilder to string conversion in java
February 14, 2018 - Disclaimer: References to any specific company, product or services on this Site are not controlled by GoDaddy.com LLC and do not constitute or imply its association with or endorsement of third party advertisers
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 115000093250-Convert-StringBuilder-to-String-concatenation-suggestion
Convert StringBuilder to String concatenation suggestion – IDEs Support (IntelliJ Platform) | JetBrains
February 22, 2017 - Hello Geoffrey, Inspection 'StringBuilder' can be replaced with 'String' only reports the cases when the resulting concatenation is at least as efficient or more efficient than the original code.
🌐
Dot Net Perls
dotnetperls.com › stringbuilder-tostring
C# - StringBuilder ToString: Get String - Dot Net Perls
ToString on StringBuilder returns a string. It internally converts the character buffer of the StringBuilder into a string object.
🌐
National Instruments
forums.ni.com › community › discussion forums › most active software boards › ni teststand › dotnet type stringbuilder not working as step parameter type
Solved: Dotnet type StringBuilder not working as step parameter type - NI Community
March 14, 2017 - TestStand strings implicitly convert to System.String, but not StringBuilder. You have to explicitly create a StringBuilder object using a separate TestStand step with a StringBuilder constructor call and store that StringBuilder object in an object reference variable and use that with your ...