OneBite.Dev - Coding blog in a bite size

append item in array in java

Code snippet on how to append item in array in java

String[] stringArray = {"This", "is", "a", "sample"};
String[] newArray = new String[stringArray.length + 1];
for(int i=0; i < stringArray.length; i++) {
    newArray[i] = stringArray[i];
}
newArray[stringArray.length] = "array";

// Here newArray[] is the new array with appended item

This code takes an existing string array, stringArray, and creates a new array with an additional space, newArray. It then iterates through each index of the existing array and assigns its value to the same index in the new array up until the last element of the existing array. That last element’s index in the new array is set to a new string, in this case “array”. Finally, the new array, newArray, is the resulting array with the appended item.

java