Technically speaking, the +
operator in Java implies the use of a StringBuilder
object when one of the operands is a string. The Java compiler (not the JVM) translates this syntactic sugar to bytecode instructions that invoke methods of the StringBuilder
object to perform the concatenation.
The exact equivalent of the piece of code in the question is:
public boolean hasOne(int n) {
StringBuilder sb = new StringBuilder();
sb.append(n); // Which does Integer.getChars(i, spaceNeeded, value);
sb.append("");
return sb.toString().contains("1");
}
As mentioned in other answers to this question, the n + ""
construct is by no means an efficient way to convert a primitive integer value to a string - using Integer#toString(int)
is definitely the recommended way to do this.
EDIT:
While for the official Oracle JVM "" + n
is definitely slower, as it always has been, I have encountered some confusing results while benchmarking on my OpenJDK JVM. While I still stand by my statement that "" + n
is sort of an anti-pattern for both performance and clarity reasons, the performance discrepancy I see on OpenJDK is quite interesting.