Change array size in java

No, we cannot change array size in java after defining.

Note: The only way to change the array size is to create a new array and then populate or copy the values of existing array into new array or we can use ArrayList instead of array.

Example: Custom Approach

public class Main
{   
   public static void main(String[] args) {
    	int[] numberArray = { 12, 24, 63, 45 };
    	System.out.println("Array before ReSize: ");
        for (int i = 0; i < numberArray.length; i++) {
            System.out.println(numberArray[i]);
        }
 
        int[] temp = new int[6];
        int length = numberArray.length;
        for (int j = 0; j < length; j++) {
          temp[j] = numberArray[j];
        }
        numberArray = temp;
 
        System.out.println("Array after ReSize: ");
        for (int i = 0; i < numberArray.length; i++) {
            System.out.println(numberArray[i]);
        }
   }
}

Output

Array before ReSize: 
12
24
63
45
Array after ReSize: 
12
24
63
45
0
0

Example: Using System.arraycopy()

import java.util.Arrays;
 
public class Main
{   
   public static void main(String[] args) {
    	int[] numberArray = { 12, 24, 63, 45 };
    	System.out.println("Array before ReSize: ");
        for (int i = 0; i < numberArray.length; i++) {
            System.out.println(numberArray[i]);
        }
 
        numberArray = Arrays.copyOf(numberArray, 6);
        numberArray[4] = 11;
        numberArray[5] = 55;
 
        System.out.println("Array after ReSize: ");
        for (int i = 0; i < numberArray.length; i++) {
            System.out.println(numberArray[i]);
        }
   }
}

Output

Array before ReSize: 
12
24
63
45
Array after ReSize: 
12
24
63
45
11
55

Interview Questions on Arrays

Please Share