Monday, January 4, 2010

String builder using variable args

In many cases, we may have to append large number of strings to get a complete string which is desired by the program. One example can be the SQL string where you are appending the values to a sql string in java.

When it comes to appending large amount of strings, it better to use StringBuffer or StringBuilder (StringBuilder is faster since its not synchronized).
Appending to StringBuilder using .append can increase the amount of code and if done in single line can look ugly.

To avoid this, you can use the below method which does it in a clean way by calling a method and passing all string objects as variables.

/**
* Given a continuous string variables, it appends them using a string builder and returns a string.
*
* @param strings - Variable args, a unlimited variables of type String
* @return - A string which is built from the given string variables.
*/
public static String buildString(String... strings) {

    StringBuilder sb = new StringBuilder();

    for (String str : strings) {
        sb.append(str);
    }
    return sb.toString();
}

//Some method to call the above method by passing variable args
public void someMethod () {
    String str = buildString("This", " is", " a", " long string", " which will", " be ", " appended", " to demonstrate", " variable", " args", " feature");
}

No comments:

Post a Comment