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
- Can we change array size in java?
- What is an anonymous array in java?
- Difference between array and arraylist in java?
- What are jagged arrays in java?
- Can array size be negative in java?
- Java program to find duplicate elements in an array.
- Java program to find second largest element in an array of integers.
- Java program to check the equality of two arrays.
- Find all pairs of elements in an integer array whose sum is equal to a given number.
- Java program to find continuous sub array whose sum is equal to a given number
- Java program to find the intersection of two arrays
- Java program to separate zeros from non-zeros in an integer array
- Java program to find all the leaders in an integer array
- Java program to find a missing number in an integer array
- Java program to convert an array to ArrayList and an ArrayList to array
- Java program to count occurrences of each element in an array
- Java program to reverse an array without using an additional array
- Java program to remove duplicate elements from an array
- Java program to find union and intersection of multiple arrays
- Java program to find the most frequent element in an array