Sully Brooks Sully Brooks - 3 months ago 15
Java Question

Add characters to an empty String after it is initialized

Just curious as to how I would add a letter or character to a pre-existing

string
.

Here is what I'm trying to do,

I'm taking a key and its cipher text and subtracting their values (stored in arraylist) to find the plaintext value (I get an int, and then use that to find the String value in the arraylist) and then continue to do that for each letter in the two strings(Cipher and Key).

Is this possible, or would I have to use a
substring
or something along those lines.

Any suggestions on how to do this, or the answer to my initial question is greatly appreciated!

Thanks,

Answer

Did you look into

StringBuilder#append()

Adding characters to String Object is not recommended since String is immutable which will create a new object everytime (if the string you are creating is not already in String pool)

Update :

If you are looking for performance too, (and by any change there are a lot of string comparisons in your program) here is my suggestion:

use strRef1 == strRef2 instead of strRef1.equals(strRef2)

Since, String is immutable and the concept of String pool the references of Strings will always be equal so if

strRef1.equals(strRef2) returns true strRef1 == strRef2 should always return true.

Exception : this would not work if you create a new string explicitly like

strRef2 = new String();