I have an array, defined as below:
String[] letters = {"ab", "cd", "ef", "gh"};
How would I go about adding an item to this array?
1.Arrays are fixed in size
2.Before declaring an array we should know the size in advance.
3.We cannot add anything dynamically to an array once we declare its size.
I recommend you to go for collection framework like List or Set where you can increase the size dynamically
By using this type of array initialization you cannot simply add more elements.
String[] letters = {"ab", "cd", "ef", "gh"};
Could be paraphrased as:
String[] letters = new String[4];
letters[0] = "ab";
letters[1] = "cd";
letters[2] = "ef";
letters[3] = "gh";
So, your array's length is only 4. To add more elements you should somehow copy you array to a bigger one and add elements there. Or just use ArrayList which does the hard work for you when capacity is exceeded.
Java arrays having static size. One you define the size of a array, it can't grow further dynamically.
Your letters array has a size of 4 element. So, you can't add more element to it.
Use ArrayList instead
List<String> letters = new ArrayList(); // Java 7 and upper versions
letters.add("ab");
letters.add("cd");
....// You can add more elements here
This is not possible without a workaround like http://www.mkyong.com/java/java-append-values-into-an-object-array/
try ArrayList, List, Map, HashMap or something like this instead
Listinstead?List