From a technical point of view, the + operator in Java implies the use of a StringBuilder object, when one of the operands is a string, the Java Compiler (and not the JVM) translates this syntactic sugar into bytecode instructions that call StringBuilder methods to perform concatenation.
The exact equivalent of the piece of code in the question:
public boolean hasOne(int n) { StringBuilder sb = new StringBuilder(); sb.append(n);
As mentioned in other answers to this question, the n + "" construct is not an efficient way to convert a primitive integer value to a string - using Integer#toString(int) definitely the recommended way to do this.
EDIT:
While the official Oracle JVM "" + n definitely slower, as it always has been, I came across some confusing results comparing my OpenJDK JVMs. Although I still adhere to my claim that "" + n is a kind of anti-pattern both in terms of performance and clarity, the rather low performance mismatch that I see on OpenJDK.
thkala May 19 '14 at 10:32 a.m. 2014-05-19 22:32
source share