InterviewSolution
| 1. |
Can we increase the size of a Java array after its declaration? |
|
Answer» The size of a primitive array cannot be increased in Java as it is fixed. If we try to increase the size of the primitive array, it would lead to an ArrayIndexOutOfBoundsException. import java.util.*; public class EXAMPLE { public static void main(String args[]) { int size=10; int arr[]=new int[size]; for(int i=0;i<10;i++) // initializing the array with values from 0 to 9 { arr[i]=i; } size++; // trying to increase the size and then initialize the 11th element present at 10TH index arr[size-1]=2; } }The OUTPUT is as follows: $javac Example.java $java Example Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Example.main(Example.java:14)The code generates an java.lang.ArrayIndexOutOfBoundsException exception. To increase the size of an array, we need to copy it and increase its size dynamically. The java.util.Arrays class provides Arrays.copyOf() METHOD which helps us to create a new array with an increased size and copy the values of the elements of the original array simultaneously. The syntax: Arrays.copyOf(original_array,new_size);Let us see an example where we copy an array and increase its size: import java.util.Arrays; public class Example { public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,7,8}; // array arr has 8 elements System.out.println("Inital array size: "+arr.length); // copying the array arr and increasing its size to 10 int[] crr = Arrays.copyOf(arr, 10); System.out.println("Final array size: "+crr.length); } }The output is as follows: $javac Example.java $java Example Inital array size: 8 Final array size: 10We can use the ArrayList class to create a dynamic array list but that would occupy a lot more memory. Thus we use the Arrays.copyOf() method. |
|