No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:

int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
    oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;

If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:

List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());

Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:

class Myclass {
    private int[] items;

    public int[] getItems() {
        return items;
    }
}

you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:

class Myclass {
    private List<Integer> items;

    public List<Integer> getItems() {
        return Collections.unmodifiableList(items);
    }
}
Answer from cletus on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ creating-a-dynamic-array-in-java
Dynamic Array in Java - GeeksforGeeks
November 13, 2024 - Arrays are linear data structures, and similar types of elements will be inserted in continuous memory locations. Now as we know there is an issue with arrays that size needs to be specified at the time of declaration or taken from the user in Java. Hence, there arise dynamic arrays in Java in which entries can be added as the array increases its size as it is full.
Top answer
1 of 16
192

No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:

int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
    oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;

If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:

List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());

Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:

class Myclass {
    private int[] items;

    public int[] getItems() {
        return items;
    }
}

you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:

class Myclass {
    private List<Integer> items;

    public List<Integer> getItems() {
        return Collections.unmodifiableList(items);
    }
}
2 of 16
32

In java array length is fixed.

You can use a List to hold the values and invoke the toArray method if needed See the following sample:

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class A  {

    public static void main( String [] args ) {
        // dynamically hold the instances
        List<xClass> list = new ArrayList<xClass>();

        // fill it with a random number between 0 and 100
        int elements = new Random().nextInt(100);  
        for( int i = 0 ; i < elements ; i++ ) {
            list.add( new xClass() );
        }

        // convert it to array
        xClass [] array = list.toArray( new xClass[ list.size() ] );


        System.out.println( "size of array = " + array.length );
    }
}
class xClass {}
Discussions

How can I make a dynamic array in Java? - Stack Overflow
Quick overview of our assignment: User needs to enter grades received. We do not know how many grades user needs to enter. If the user enters "-1" thats when we know the user is done entering grade... More on stackoverflow.com
๐ŸŒ stackoverflow.com
I can't wrap my head up around Dynamic Arrays
Java's ArrayList is a dynamic array. More on reddit.com
๐ŸŒ r/learnjava
9
0
August 12, 2022
Dynamic array in java - Stack Overflow
Can't i just keep it dynamic? the length is variable ยท No. Arrays lenght should be fixed while initializing it. Look into Collection's in java. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Variable length (Dynamic) Arrays in Java - Stack Overflow
I was wondering how to initialise an integer array such that it's size and values change through out the execution of my program, any suggestions? More on stackoverflow.com
๐ŸŒ stackoverflow.com
People also ask

Can a dynamic array in Java (specifically ArrayList) effectively store null elements?
Yes, an ArrayList, as a dynamic array in Java, permits null values as valid elements. This design choice offers flexibility in representing absent data. However, consuming code must explicitly handle these null references. Failing to validate fetched elements can lead to NullPointerException issues.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ creating a dynamic array in java
Dynamic Array in Java: Secret Behind High-Performance Code!
How does initial capacity influence the performance of a dynamic array in Java?
Specifying an appropriate initial capacity significantly reduces re-allocation frequency. This preemptive provisioning minimizes O(n) element copying overhead during early growth. It helps prevent costly heap movements impacting runtime efficiency. Optimal initial sizing directly improves the startup throughput for your application.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ creating a dynamic array in java
Dynamic Array in Java: Secret Behind High-Performance Code!
What performance trade-offs exist between using ArrayList versus a fixed-size raw array in Java?
ArrayList provides dynamic resizing and a high-level, convenient API for flexible data management. Raw arrays offer compile-time size guarantees and marginally lower per-element object overhead. ArrayList manages internal array details, abstracting complexity from developers. Choose based on required runtime flexibility versus strict memory control.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ creating a dynamic array in java
Dynamic Array in Java: Secret Behind High-Performance Code!
๐ŸŒ
Interview Cake
interviewcake.com โ€บ concept โ€บ java โ€บ dynamic-array
Dynamic Array Data Structure | Interview Cake
Just like arrays, elements are stored adjacent to each other. So adding or removing an item in the middle of the array requires "scooting over" other elements, which takes time. In Java, dynamic arrays are called ArrayLists.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ dynamic array in java
Dynamic Array in Java - Scaler Topics
May 4, 2023 - In order to mitigate the sizing ... concept of dynamic data structures in Java. As the name suggests, dynamic arrays have a dynamic size modifiable at runtime....
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ blog โ€บ software development โ€บ creating a dynamic array in java
Dynamic Array in Java: Secret Behind High-Performance Code!
June 12, 2025 - Step 4: While an individual re-allocation is O(n) (linear time complexity), the amortized cost for a sequence of additions averages O(1). This makes the dynamic ยท array in Java highly efficient for most growth patterns.
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ dynamic array in java | working, uses & more (+examples)
Dynamic Array In Java | Working, Uses & More (+Examples)
January 10, 2025 - A dynamic array in Java, like ArrayList, is a resizable array that can grow or shrink as needed, unlike fixed-size arrays, offering greater flexibility.
Find elsewhere
๐ŸŒ
Edureka
edureka.co โ€บ blog โ€บ dynamic-array-java
What is Dynamic Array in Java? | How do they Work? | Edureka
June 17, 2021 - The dynamic array in Java is a type of an array with a huge improvement for automatic resizing. The only limitation of arrays is that it is a fixed size.
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ java tutorial โ€บ dynamic array in java
Dynamic Array in Java | How does Dynamic Array work in Java?
May 13, 2024 - When we try to insert the third element, the array capacity increases to 4 (as we specify capacity=2*initial size). So, we can be able to add the 3rd element also. Line 4 displayed all the array elements. Removing the elements from an array and reducing size and capacity dynamically. This example is the continuation of the above example. ... package com.dynamicarray; import java.util.Arrays; public class DynamicArray { // declaring an array int myArray[]; // stores the present size of the array int sizeOfMyArray; // stores total capacity of an array int arrayCapacity; // initializing array, si
Call ย  +917738666252
Address ย  Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
๐ŸŒ
Java Code Geeks
examples.javacodegeeks.com โ€บ home โ€บ java development โ€บ core java
Dynamic Array Java Example - Java Code Geeks
October 18, 2021 - DynamicArray class provides operations to add and remove items from an array. ... import java.util.Arrays; public class DynamicArray{ private int array[]; // holds the current size of array private int size; // holds the total capacity of array ...
Top answer
1 of 4
3

You can't make dynamic array in java.

For that you will have to use List or ArrayList.

We will have to provide the size of array before application run or at coding time, while arrayList gives us facility to add data while we need it, so it's size will automatically increased when we add data.

Example :

import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);
      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}

this example is from here.

UPDATE :

When you define your list as:

List myList = new ArrayList(); you can only call methods and reference members that belong to List class. If you define it as:

ArrayList myList = new ArrayList(); you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.

List is not a class it is an interface. It doesn't have any methods implemented. So if you call a method on a List reference, you in fact calling the method of ArrayList in both cases.

2 of 4
1

Using some kind of List is a better choice, as it basically does what you want (can grow and shrink), in fact, ArrayList is just that, a dynamic array.

You can hand roll your own if you can't use a List using System.arraycopy

For example, this will grow or shrink an array to match the size you provide...

public String[] updateArray(String[] src, int size) {

    String[] dest = new String[size];
    if (size > src.length) {

        System.arraycopy(src, 0, dest, 0, src.length);

    } else {

        System.arraycopy(src, 0, dest, 0, size);

    }

    return dest;

}

Again... List is easier...

๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ java-program-dynamic-array
Dynamic Array in Java - Sanfoundry
March 9, 2023 - A dynamic array is an array that can change its size during runtime. In Java, dynamic arrays are implemented using the ArrayList class.
๐ŸŒ
Study.com
study.com โ€บ courses โ€บ business courses โ€บ java programming tutorial & training
Java: Dynamic Arrays - Lesson | Study.com
October 12, 2018 - He is an adjunct professor of computer science and computer programming. ... Java is a type of programming language cannot accommodate dynamic arrays unless a different approach is used.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ java dynamic array
How to Create a Dynamic Array in Java | Delft Stack
February 2, 2024 - The array size is the number of items in it, and an arrayโ€™s capacity is the total space in it. We create a constructor of the DynamicArrayTest class and initialize intArray with an int array having the size of 2. Then, we initialize the size with 0 and capacity as 2.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ i can't wrap my head up around dynamic arrays
r/learnjava on Reddit: I can't wrap my head up around Dynamic Arrays
August 12, 2022 -

Recently I have been learning data structures I understand the concept but not 100% and in java I didn't understand the code that the guy in the video I have been watching to learn it so can any one help me with this (Sorry for my English)

Top answer
1 of 4
2
Java's ArrayList is a dynamic array.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
Medium
medium.com โ€บ swlh โ€บ how-to-build-a-dynamic-array-by-using-a-static-array-in-java-5c455a69c7b4
How to Build a Dynamic Array By Using a Static Array in Java | by Vindya Gunawardana | The Startup | Medium
September 4, 2020 - A dynamic array automatically grows when we try to make an insertion and there is no space left for the new item. A simple dynamic array can be constructed, by using an array of fixed-size. The elements of the array are stored contiguously, for an instance, if it is an integer type array it will take 4 bytes of space per integer element.
๐ŸŒ
Medium
pranathisadhula.medium.com โ€บ how-to-create-dynamic-array-without-using-arraylist-or-any-other-collections-5796533a95cb
How to create Dynamic Array (without using ArrayList or any other collections) | by Pranathisadhula | Medium
December 29, 2020 - Using copyOf() method available in Java Arrays class and the above newLength value, we can increase the size as below : initialArray = Arrays.copyOf(initialArray, newLength); This way we can dynamically insert elements into our traditional Array without using java collections like arraylist.
๐ŸŒ
Quora
quora.com โ€บ How-can-I-initialize-an-array-in-Java-dynamically
How to initialize an array in Java dynamically - Quora
Elements get Java default values (0, false, null). Fill with loops, Arrays.fill, or streams. ... Initializing arrays dynamically in Java means creating an array whose size or contents are determined at runtime (not hard-coded).