Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char Array vs String: which is better for storing a set of letters

I need to store in a constant class 4 letter of a code. I can do:

static final String CODE_LETTERS = "TRWAG";

or

static final char[] CODE_LETTERS = {'T', 'R', 'W', 'A', 'G'};

After, I can obtain one of that characters in two ways:

final char codeLetter = CODE_LETTERS.charAt(index);

or

final char codeLetter = CODE_LETTERS[index];

what is the best way?. Please take in mind correction, performance, etc.

like image 242
xgomez Avatar asked Apr 29 '09 10:04

xgomez


People also ask

Which is better char array or string?

We should always store the secure information in char[] array rather than String. Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it.

Which is faster string or char array?

So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.

Why do we prefer char arrays instead of strings to store passwords?

Character arrays ( char[] ) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[] is used, after purging data with 0's, the password is secure. Not secure by default.

What is difference between char array and string?

String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char. Strings are immutable.


1 Answers

Neither is incorrect, but since you're going to be dealing with the chars individually I'd personally use the char []. That said, the impact this will have on performance is going to be negligible if even measurable.

like image 101
Eoin Campbell Avatar answered Sep 19 '22 17:09

Eoin Campbell