-2

For the following code, how would I use concatenation instead of StringBuilder to create the string in the following method? My teacher said to use concatenation and not StringBuilder.

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }
H98
  • 1
  • 3
  • Welcome to SO! Concatenation is slower than StringBuilder. What is your rationale in doing this? You can use `String s = ""; s += (char)cp;` if you must... – ggorlen Jun 11 '19 at 20:42
  • 4
    Using `String` instead of `StringBuilder` and `+=` instead of `.append()`. Why would you want that, by the way? There is literally no benefit, apart from changing something from friend's homework. – Fureeish Jun 11 '19 at 20:43
  • `string += (char)cp;` – luk2302 Jun 11 '19 at 20:43
  • 1
    Concatenation is generally not preferred if you are handling too many strings. It would create too many strings as string is not mutable. If you are dealing with few strings you can concatenate using sb.concat( ) (Your sb object should of type String) – Nikitha Jun 11 '19 at 20:44
  • @NikithaVangala That's not necessarily true. String concatenation (outside of loops) compiles to use `StringBuilder`. – Jacob G. Jun 11 '19 at 20:46
  • You can just use this: `new BufferedReader(rd).lines().collect(Collectors.joining("\n"));` – Samuel Philipp Jun 11 '19 at 20:48
  • @jacob G Thank you for pointing out. It is answered here https://stackoverflow.com/questions/18453458/string-builder-vs-string-concatenation – Nikitha Jun 11 '19 at 20:53

1 Answers1

0

This is a fairly simple question. however as others have stated this code will run slower then your original code but for knowledge here is the answer

private static String readAll(Reader rd) throws IOException {
    String s = "";
    int cp;
    while ((cp = rd.read()) != -1) {
        s += ((char) cp);
    }
    return s;
}
azro
  • 53,056
  • 7
  • 34
  • 70
caleb baker
  • 144
  • 7