Java Array add elements With Examples

How to add elements to an array in java? We know that java array size is fixed, so we can’t add elements to an Array. We have to provide size of the array when we initialize array in java.

Java Array add elements

java-array-add-elements

There is no shortcut method to add elements to an array in java. But as a programmer, we can write one. Here I am providing a utility method that we can use to add elements to an array. We can also use it for java copy arrays.

In the utility method, I will create a temporary array, whose size will be the addition of the length of array and number of elements to add in the array. Then I will copy the input array to the temporary array and add the elements and then return it.

Let’s see this in action.

I am using variable arguments in add() so that we can pass any number of objects to be added to the array. Note that the array type should be Object else it will throw ClassCastException.
Also, this will work only for Object array and not for primitive data types array.

Output of the above program is:

This is just an alternative way to add Objects to an array in java but we should use ArrayList in this scenario where the number of elements can change.

Reference: Arrays

By admin

Leave a Reply