Skip to main content

APIzation: Replication Package

[Q#20938726][A#20938772] How does the concatenation of a String with characters work in Java?

https://stackoverflow.com/q/20938726

The following is a problem from codingbat. Given a string, return a string where for every char in the original, there are two chars. e.g.: I have two statements that can do this, but the statement in the comment doesn't give the excepted output: If I change the commented part to str1 = str1 + str.charAt(i) + str.charAt(i), the output is as required. I am not able to understand this. If the concatenation doesn't, then it shouldn't work for either of the case. Can you help me in this?

Answer

https://stackoverflow.com/a/20938772

str.charAt(i) returns a char, adding two chars results in a char with a codepoint equal to the sum of the input codepoints. When you start with str +, the first concatenation is between a String and a char, which results in a String, followed by the second concatenation, also between a String and a char. You can fix this a few ways, such as: or or, as you've already discovered, and likely the most readable:

APIzation

str1 += String.valueOf(str.charAt(i)) + str.charAt(i);
str1 += "" + str.charAt(i) + str.charAt(i);
str1 = str1 + str.charAt(i) + str.charAt(i);
package com.stackoverflow.api;

public class Human20938772 {

  public static String doubleString(String str) {
    String str1 = "";
    for (int i = 0; i < str.length(); i++) str1 +=
      String.valueOf(str.charAt(i)) + str.charAt(i);

    return str1;
  }
}

package com.stackoverflow.api;

/**
 * How does the concatenation of a String with characters work in Java?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/20938772">https://stackoverflow.com/a/20938772</a>
 */
public class APIzator20938772 {

  public static void work(int i, String str1, String str)
    throws Exception {
    str1 += String.valueOf(str.charAt(i)) + str.charAt(i);
    str1 += "" + str.charAt(i) + str.charAt(i);
    str1 = str1 + str.charAt(i) + str.charAt(i);
  }
}