how to dynamically declare an array in java code example

Example 1: dynamic array in java

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
    private int capacity;
     
    // default constructor to initialize the array and values
    public DynamicArray(){
        array = new int[2];
        size=0;
        capacity=2;
    }
     
    // to add an element at the end
    public void addElement(int element){
        // double the capacity if all the allocated space is utilized
        if (size == capacity){
            ensureCapacity(2); 
        }
        array[size] = element;
        size++;
    }

Example 2: how to create dynamic string array in java

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Example 3: how to create dynamic string array in java

List<String> zoom = new ArrayList<>();
zoom.add("String 1");
zoom.add("String 2");

for (String z : zoom) {
    System.err.println(z);
}

Tags:

Java Example