In this case, excellent with the + tag. This is more readable, and it is the same as execution compared to the version of StringBuilder/StringBuffer , since it does not happen inside the loop.
If you are building a String inside a loop, then most often you should use StringBuilder . Use StringBuffer only if you need its synchronized function, which does not happen very often.
Simplified (not always, but this is a good rule), if you do not do += with String , you really don't need StringBuilder/StringBuffer .
Related Questions
- StringBuilder vs String Concatenation in toString () in Java
- String, StringBuffer, and StringBuilder
- StringBuilder and StringBuffer in Java
A String.format option
One option that is often not considered is to use String.format . It will look something like this:
return String.format("POJO : %s RollNo %s : Name : %s", this.getClass().getName(), this.rollNo, this.name );
I believe that this is the most readable and supported version.
It's faster? Maybe yes maybe no. Usually this does not matter for sharing scripts for something like toString() . Strive for readability, only optimize if profiling says it is necessary.
API Links
In the literal class
I fixed a syntax error in the source code from this.class (which does not compile) to this.getClass() .
see also
Related Questions
- What is a class literal in Java?
polygenelubricants
source share