How to create an array in rexx

How to add new elements to an array in Java

  1. Use a
  2. Create a new larger array

This tutorial will discuss how to add new elements to an array in Java.

in Java is a container object that contains a fixed number of elements of the same data type. The length of the array is specified when the array object is declared and cannot be changed later.

Suppose we instantiated an array of length 5 in Java with some values:

Now there is a requirement to add a 6th element to our array. Now let's try to add this 6th element to our array.

The above line of code gives the following error:

That's because we initially declared the array to be size 5 and tried to get a 6.

Don't worry, there are 2 possible solutions to achieve this. We can use one instead of an array or create a new larger array to hold new elements.

Use a

A better and recommended solution is to use an instead of an array as it is resizable. There's no fixed size of, so whenever you need to add a new item, you can add it just by running.

The above code outputs the following.

Or if we already have an array, we can also create one directly.

The above code outputs the following.

We can easily convert one back to an array.

Create a new larger array

If we insist on working with arrays only, we can use the method to create a larger array and include a new element. Let's use the array we created above and add a new element in the example below.

The above code outputs the following.

If later we feel the need to add another element, we have to repeat the code block above again!

Hence, this solution is not recommended because adding each new element has a time complexity of copying all elements from the previous array to a new array. On the other hand, adding each new item has an amortized cost per operation by means of.

Related Article - Java Array

  • Print 2D array in Java
  • Convert Char array in Java to Int