how to change the size of array in java

https:/‮.www/‬lautturi.com
how to change the size of array in java

Once an array is created, you cannot change its size.

If you need to change the size, create a new array and copy the elements to new array.

/**
 * @author lautturi.com 
 * Java example: change the size of array in java
 */

import java.util.*;

public class Lautturi {

	public static void main(String[] args) {

		int[] arr = { 1, 3, 5, 2, 4 };
		System.out.println(Arrays.toString(arr));

		int newArr[] = new int[10];

		newArr = Arrays.copyOf(arr, 10);

		System.out.println(Arrays.toString(newArr));

		newArr[5] = 10;
		newArr[7] = 12;

		arr = newArr;
		System.out.println(Arrays.toString(arr));

	}
}

output:

[1, 3, 5, 2, 4]
[1, 3, 5, 2, 4, 0, 0, 0, 0, 0]
[1, 3, 5, 2, 4, 10, 0, 12, 0, 0]
Created Time:2017-09-24 23:25:11  Author:lautturi