Look at java.util.LinkedList or java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Answer from corsiKa on Stack Overflow
Top answer
1 of 11
114

Look at java.util.LinkedList or java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
2 of 11
67

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

A bit similar to the PHP behaviour is this:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

Then you can write:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

🌐
W3Schools
w3schools.com › java › java_arrays.asp
Java Arrays
Use new with a size when you want to create an empty array and fill it later. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Discussions

How to add something to primitive array in Java?
Allocate a new bigger array, copy existing values over, add the new one. You probably don't really want to be using an array for what you're doing if you're doing this a lot. More on reddit.com
🌐 r/learnprogramming
15
1
December 2, 2015
java - How to add new elements to an array? - Stack Overflow
I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure. ... and you want to add some elements to it like numbers please us StringBuilder which is much ... More on stackoverflow.com
🌐 stackoverflow.com
Add an Array to an ArrayList
I’ve created a REALLY simple code snippet to show what I’m trying to do. I need to add an array that I have defined into an ArrayList. I need an ArrayList as I don’t know how many arrays I will end up with. This will Obvs be in a loop but I just wanted to show the problem I’m having ... More on discourse.processing.org
🌐 discourse.processing.org
1
1
January 5, 2020
java - equivalent to push() or pop() for arrays? - Stack Overflow
I am trying to add, remove and reference items from an array I create in my main java file, but I am having trouble figuring out the correct syntax. In actionscript they have push() and pop() for ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › java › ref_arraylist_add.asp
Java ArrayList add() Method
Arrays Loop Through an Array Real-Life Examples Multidimensional Arrays Code Challenge · Java Methods Java Method Challenge Java Method Parameters
🌐
Reddit
reddit.com › r/learnprogramming › how to add something to primitive array in java?
r/learnprogramming on Reddit: How to add something to primitive array in Java?
December 2, 2015 -

Hi all, so I have an empty array I just created like this:

int[] array = new int[5];

How do I add numbers to it? I tried array.append() but it's not working. I don't want to do it manually like array[0] etc I want to just keep adding to the tail.

EDIT: I'm sure I won't go over the limit of what the array can contain. I just want to know how to add to the tail of the array without having to specify what position is being added.

Top answer
1 of 16
477

The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.

A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.

List<String> where = new ArrayList<String>();
where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );

If you need to convert it to a simple array...

String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );

But most things you do with an array you can do with this ArrayList, too:

// iterate over the array
for( String oneItem : where ) {
    ...
}

// get specific items
where.get( 1 );
2 of 16
124

Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).

import java.util.*;
//....

List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
System.out.println(list); // prints "[1, 2, 3]"

If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.

static <T> T[] append(T[] arr, T element) {
    final int N = arr.length;
    arr = Arrays.copyOf(arr, N + 1);
    arr[N] = element;
    return arr;
}

String[] arr = { "1", "2", "3" };
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
arr = append(arr, "4");
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"

This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.

See also

  • Java Tutorials/Arrays
    • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
  • Java Tutorials/The List interface
🌐
Educative
educative.io › answers › how-to-append-to-an-array-in-java
How to append to an array in Java
The question is: how do you add things to your array without breaking it? That’s where this Answer comes in! ... Java arrays can’t grow once they have been created; so, to add an element, you need to use the one of the following methods:
Find elsewhere
🌐
Coderanch
coderanch.com › t › 745116 › java › add-elements-array-arrays
How to add elements to an array of arrays (Java in General forum at Coderanch)
August 26, 2021 - So you can add things to ArrayLists and other collections, but the Array will never grow, it will be of fixed size, determined at creation. RTFJD (the JavaDocs are your friends!) If you haven't read them in a long time, then RRTFJD (they might have changed!)
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-add-an-element-to-an-array-in-java
How to Add an Element to an Array in Java? - GeeksforGeeks
October 16, 2025 - Add the n elements of the original array to this array. Add the new element in the n+1th position. Print the new array. ... // Java Program to add an element // into a new array import java.io.*; import java.lang.*; import java.util.*; class ...
🌐
Medium
medium.com › @kowsikratnagiri › i-thought-i-knew-java-the-jvm-proved-me-wrong-9403b84087be
I Thought I Knew Java. The JVM Proved Me Wrong. | by Kowsik Ratnagiri | Mar, 2026 | Medium
5 days ago - First: the Local Variable Table, an array of slots holding the method's parameters and local variables (primitives stored directly, object references stored as heap pointers). Second: the Operand Stack, a last-in first-out evaluation stack that bytecode uses to perform computations — pushing values on, popping and operating on them, pushing results back. Third: a reference to the class's Constant Pool. Fourth: the Return Address ...
🌐
Quora
quora.com › How-can-I-append-a-number-into-a-java-array
How to append a number into a java array - Quora
Pass the integer to the add() method. This will append the integer to the end of the array. ... Reduce damage from data leaks. Eligible financial losses tied to identity misuse may be reimbursed.
🌐
JanBask Training
janbasktraining.com › community › java › how-to-add-new-elements-to-an-array
How to add new elements to an array? - Java
September 2, 2025 - Use unshift() to add elements at the beginning. Use splice() to insert elements at any position. ... Arrays in Java have fixed sizes, so you can’t directly add elements.
🌐
Jsnover
jsnover.com › blog › 2026 › 03 › 13 › microsoft-hasnt-had-a-coherent-gui-strategy-since-petzold
Microsoft Hasn’t Had a Coherent GUI Strategy Since Petzold | Jeffrey Snover's blog
1 week ago - Uno Platform – WinUI APIs on every platform. More committed to WinUI than Microsoft is. Delphi / RAD Studio – Still alive. Still fast. Still in vertical market software. Java Swing / JavaFX – Yes, still in production.
🌐
Wikipedia
en.wikipedia.org › wiki › Generics_in_Java
Generics in Java - Wikipedia
4 days ago - However, if the developer attempts to add a String to this Long[] object, the program will throw an ArrayStoreException. This run-time exception can be completely avoided if the developer uses generics. If the developer declares a Collection<Object> object an creates a new instance of this object with return type ArrayList<Long>, the Java compiler will (correctly) throw a compile-time exception to indicate the presence of incompatible types (since generics are invariant).
🌐
W3Schools
w3schools.com › java › java_arrays_loop.asp
Java Loop Through an Array
Java Examples Java Videos Java ... Java Certificate ... You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › ArrayList.html
ArrayList (Java Platform SE 8 )
5 days ago - The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation. Each ArrayList instance has a capacity.
🌐
LeetCode
leetcode.com › problems › running-sum-of-1d-array
Running Sum of 1d Array - LeetCode
We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained ...
Top answer
1 of 5
56

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

2 of 5
25

For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:

array = push(array, item);

The drawbacks are that

  • the whole array has to be copied each time you push, and
  • the original array Object is not changed, so you have to update the variable(s) as appropriate.

Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    for (int i = 0; i < array.length; i++)
        longer[i] = array[i];
    longer[array.length] = push;
    return longer;
}

This alternative is more efficient, shorter & harder to read:

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    System.arraycopy(array, 0, longer, 0, array.length);
    longer[array.length] = push;
    return longer;
}