OneBite.Dev - Coding blog in a bite size

insert an element at the end of an array in java

Code snippet on how to insert an element at the end of an array in java

int[] numbers = {1,2,3,4,5};
int n = 6;

//Create a new array with one extra element
int[] newNumbers = new int[numbers.length + 1];

//Copy items from old array to new
for(int i = 0; i < numbers.length; i++) {
    newNumbers[i] = numbers[i];
}

//Add the new element at the end of the new array
newNumbers[newNumbers.length-1] = n;

This code adds an element to the end of an array. First it creates a new array with one more element than the initial array by using the length attribute. Then it loops through the initial array to copy items from the initial array to the created array. Finally it adds the new element to the end of the created array by using the length attribute of the new array.

java