Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: cannot convert from StringBuilder to String

Tags:

java

android

This method returns the source of the given URL.

private static String getUrlSource(String url) {
    try {
        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;
    } catch (Exception e) {
        Log.e("ERR",e.getMessage());
    }
}

It gives me this error:

Type mismatch: cannot convert from StringBuilder to String

And two choices:

  1. Change the return type to StringBuilder. But I want it to return a String.
  2. Change type of ma to String. After changing a String has no append() method.
like image 303
user2301855 Avatar asked Apr 22 '13 20:04

user2301855


People also ask

Can StringBuilder be converted to String?

To convert a StringBuilder to String value simple invoke the toString() method on it. Instantiate the StringBuilder class. Append data to it using the append() method. Convert the StringBuilder to string using the toString() method.

Can we convert String to StringBuilder in Java?

Converting a String to StringBuilder The append() method of the StringBuilder class accepts a String value and adds it to the current object. To convert a String value to StringBuilder object just append it using the append() method.

What is StringBuilder in java?

StringBuilder in Java is a class used to create a mutable, or in other words, a modifiable succession of characters. Like StringBuffer, the StringBuilder class is an alternative to the Java Strings Class, as the Strings class provides an immutable succession of characters.


2 Answers

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
like image 182
BackSlash Avatar answered Oct 19 '22 05:10

BackSlash


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);
like image 3
Gowsik Raja Avatar answered Oct 19 '22 07:10

Gowsik Raja