Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my Java string concatenation work?

When this code runs, it gets the content of a webpage.

I wanted to concatenate that entire string rather than printing it to the console but when I uncomment the two lines in the code below, System.out.println(inputLine); prints nothing (but it worked with the line below commented) and the value fileText = null,

where does this error come from?

import java.net.*;
import java.io.*;

public class URLReader {

    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.oracle.com");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String fileText = "";
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            //fileText.concat(inputLine);
            System.out.println(inputLine);
        in.close();
        //System.out.println(fileText);
    }
}
like image 648
guillaume guerin Avatar asked Mar 21 '26 18:03

guillaume guerin


1 Answers

String is immutable and concat() will return a new String (check the linked doc), which you're not collecting.

You should make use of a StringBuilder to build a string efficiently, and then call toString() on that once you're complete to get he resultant String.

e.g.

StringBuilder sb = new StringBuilder();
while (....) {
   sb.append("more string data");
}
String str = sb.toString();

You can append Strings e.g.

   str = str + "more string data";

but it's not very efficient, due to the implementation of String. A StringBuilder is built in order to perform concatenation efficiently. You can tune a StringBuilder via its initial capacity if you have an idea of the size of String you're building.

You may see some sources refer to a StringBuffer. That's very similar, except it's older and synchronises its methods by default. In a non-threaded environment that's wasteful and the general advice is to prefer StringBuilder.

like image 175
Brian Agnew Avatar answered Mar 24 '26 07:03

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!