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.
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.
So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.
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.
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.
Neither is incorrect, but since you're going to be dealing with the char
s individually I'd personally use the char []
. That said, the impact this will have on performance is going to be negligible if even measurable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With