In this tutorial, we will learn to write a Java program to insert an element at the end of an array and print the array. Our program will insert an element at the end of the given array (list).
For example
Case 1: If the given array is {1, 2, 3, 4} and the user enters 9 to add an element at the end, the output should be {1, 2, 3, 4, 9}.
Case 2: if the given array is {9, 2, 4, 8} and the user makes the input 10 to add an element at the end, the output should be {9, 2, 4, 8, 10}.
Insert Element At the End of Array in Java
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Java Program to insert element at end of Array");
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size + 1];
for (int i = 0; i < size; i++) {
System.out.print("Please give value for index " + i + " : ");
arr[i] = sc.nextInt();
}
System.out.print("Enter the element to insert at end: ");
arr[size] = sc.nextInt();
System.out.println("Array After Inserting " + arr[size] + " at end");
for (int i = 0; i < size + 1; i++) {
System.out.println(arr[i]);
}
}
}
Explanation
For the given array {1, 2, 3, 4, 5 }, the user enters element 6 to be added to the end of the array. Using the arr[size] method, our program simply adds the element 6 to the end of the list and returns the updated list.
Output
Java Program to insert element at end of Array
Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
Enter the element to insert at end: 6
Array After Inserting 6 at end
1
2
3
4
5
6