Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder append content to a new line every time

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?

like image 857
Dark Knight Avatar asked Nov 06 '13 13:11

Dark Knight


People also ask

How do you add a new line in StringBuilder?

append("/n");

Is StringBuilder better than concatenation?

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.

How do you append the next line in a StringBuffer?

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.

Is StringBuilder less efficient or more efficient?

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.


1 Answers

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.

like image 56
StuPointerException Avatar answered Nov 02 '22 23:11

StuPointerException