1import java.util.Arrays;
2
3class ArrayAppend {
4 public static void main( String args[] ) {
5 int[] arr = { 10, 20, 30 };
6 System.out.println(Arrays.toString(arr));
7
8 arr = Arrays.copyOf(arr, arr.length + 1);
9 arr[arr.length - 1] = 40; // Assign 40 to the last element
10 System.out.println(Arrays.toString(arr));
11 }
12}
1// A better solution would be to use an ArrayList which can grow as you need it.
2// The method ArrayList.toArray( T[] a )
3// gives you back your array if you need it in this form.
4
5List<String> where = new ArrayList<String>();
6where.add(element);
7where.add(element);
8
9// If you need to convert it to a simple array...
10
11String[] simpleArray = new String[ where.size() ];
12where.toArray( simpleArray );
1//original array
2String[] rgb = new String[] {"red", "green"};
3//new array with one more length
4String[] rgb2 = new String[rgb.length + 1];
5//copy the old in the new array
6System.arraycopy(rgb, 0, rgb2, 0, rgb.length);
7//add element to new array
8rgb2[rgb.length] = "blue";
9//optional: set old array to new array
10rgb = rgb2;