0

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);
}
3
  • 2
    return "" + str1.charAt(0) + str2.charAt(0); Commented Mar 7, 2019 at 5:20
  • 1
    Side note: When you are talking about readability & maintenance, then consider changing the method name from getString to something more appropriate of the purpose of the method. Commented Mar 7, 2019 at 5:24
  • 1
    Normally I'd prefer StringBuilder but the operation here is so simple either one is about the same. Commented Mar 7, 2019 at 5:26

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

-1

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.

3 Comments

Why is a 230k user answering an obviously opinion-based question, rather than applying a close vote?
@DawoodibnKareem Maybe I'm not me, and some low rep user has hijacked my account? There are so many answers to your question, I don't even know where to begin.
However, I would vote for - yes does not sound like Tim

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.