Which of the two toString() methods below is the better one?
public String toString(){
return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append("{a:").append(a)
.append(", b:").append(b)
.append(", c:").append(c)
.append("}")
.toString();
}
More importantly, if you want to create a string with only three field values without any addition, I want to know which method is better.
stringbuilder java string performance concatenation
The first method is preferred because the representation of the source code is shorter and more concise. And the Java compiler actually converts the first method into the second method and compiles it. So there's no performance difference between the two.
© 2024 OneMinuteCode. All rights reserved.