I am building a validation routine that validates contents and then gives warning (for failures) in form of StringBuilder. Say in below code I am checking lower bound for values paramX and paramY.
StringBuilder sb= new StringBuilder();
if(paramX<10){
sb.append("paramX cannot be less than 10 ");
}
if(paramY<20){
sb.append("paramY cannot be less than 20 ");
}
System.out.println(sb);
It gives output as: paramX cannot be less than 10 paramY cannot be less than 20
but i want output such that, each appended String will be printed on new line. Like below.
paramX cannot be less than 10
paramY cannot be less than 20
I used following workarounds, but ended up repeating same code again and again(Which i don't want to).
sb.append(System.getProperty("line.separator")); // Add Explicit line separator each time
sb.append("\n");
sb.append("paramX cannot be less than 10 \n");
Is there a simpler way to do it?
append("/n");
So which should we use? It is always better to use StringBuilder. append to concatenate two string values. Let us cement this statement using the below micro benchmark.
To append new line to StringBuffer, use append method of StringBuffer class. Different operating systems uses different escape characters to denote new line. For example, in Windows and DOS it is \r\n, in Unix it is \n. To write code which works in all OS, use Java System property line.
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
If you don't want to do it over and over then write a helper method:
public void appendString(StringBuilder builder, String value) {
builder.append(value + System.lineSeparator());
}
Then call:
if(paramX<10){
appendString(sb, "paramX cannot be less than 10 ");
}
This way you only have a single place to maintain if you need to change the output format for the errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With