Rajaguru
Rajaguru

Reputation: 11

Char array or String Builder

I'd like to know for character concatenation in Java - which one of the below method would be better for readability, maintenance and performance - either 'char array' or 'string builder'.

The method has to take the first letter from both the strings, append and return it.

Eg: Input 1: ABC Input 2: DEF -> method should return AD.

using string builder:

private String getString(String str1, String str2) {
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(str1.charAt(0));
    stringBuilder.append(str2.charAt(0));
    return stringBuilder.toString();
}

using char array:

private String getString(String str1, String str2) {
    char[] charArray = new char[2];
    charArray[0] = str1.charAt(0);
    charArray[1] = str2.charAt(0);
    return String.valueOf(charArray);
}

Upvotes: 0

Views: 3036

Answers (3)

Harsh Mishra
Harsh Mishra

Reputation: 2135

charArray is good in term of Performance and readability too but it hard to maintain the code like this. It can cause the error like Null pointer. You just need to add the null check with char[] code.

On the other side StringBuffer internally use the char. So, char is better here and also by doing this we are not creating an Object. Memory point of view. It's good not to create that one.

Upvotes: 1

Shubham Chopra
Shubham Chopra

Reputation: 1737

StringBuilder is just a wrapper around a char[], adding functionality like resizing the array as necessary; and moving elements when you insert/delete etc.

It might be marginally faster to use the char[] directly for some things, but you'd lose (or have to reimplement) a lot of the useful functionality.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

If you review the source code for StringBuilder, you will find that internally it uses a char[] to represent the buffered string. So both versions of your code are doing very similar things. However, I would vote for using StringBuilder, because it offers an API which can much more than the plain char[] which sits inside its implementation.

Upvotes: -1

Related Questions