Java Program to Insert Element At the End of Array

In this tutorial, we will learn writing Java Program to insert an element at the end of an array and print the array. Our program will add 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 users give input 9 to add at last.

           The output should be {1, 2, 3, 4, 9}.

Case 2: if the given array is {9, 2, 4, 8} and the users give input 10 to add at last.

           The output should be {9, 2, 4, 8, 10}.

Java Program to Insert Element At the End of Array

Program 1: Using Iteration

import java.util.*;  
public class InsertAtEnd
{
	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]);
        }
	}
}

Output

Enter the size of array: 6
Please give value for index 0 : 4
Please give value for index 1 : 2
Please give value for index 2 : 6
Please give value for index 3 : 7
Please give value for index 4 : 2
Please give value for index 5 : 3
Enter the element to insert at end: 9
Array After Inserting 9 at end
4
2
6
7
2
3
9

Explanation

For the given array {1, 2, 3, 4, 5 }, the user inputs element 6 to add at the end of the array. Using the arr[size] method, our program will easily add element 6 at the end of the list and returns the updated list.

Program Explanation

  1. Setup: It imports necessary classes from the java.util package and initializes a Scanner to read user input.
  2. Introduction and Array Initialization: The program begins by announcing its purpose, then asks the user to specify the size of the array. The array arr is then declared with a length of size + 1 to accommodate the additional element to be added later.
  3. Populating the Array: The user is prompted to enter values for each index of the array up to the original specified size (size). These values are read from the console and stored in the respective positions in the array.
  4. Adding Element at End: The user is asked for one additional value to be inserted at the end of the array. This value is placed in the last position of the array (arr[size]).
  5. Display Updated Array: After insertion, the program prints a message indicating the element added and then displays the entire array, showing the original values plus the newly added element at the end.

Program 2: Using ArrayList for Dynamic Arrays

Java’s ArrayList provides a way to manage arrays that need to frequently change in size.

import java.util.*;  
public class InsertAtEnd
{
	public static void main(String[] args) {
	    Scanner sc = new Scanner(System.in);
	    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
	    System.out.println("Original Array ");
	    for (int value : list) {
            System.out.print(value + " ");
        }
        System.out.println("");
        System.out.println("Enter the element to insert at end: ");
        int elementToInsert= sc.nextInt();
        list.add(elementToInsert);
        System.out.println("Array After Inserting at end");
        for (int value : list) {
            System.out.print(value + " ");
        }
	}
}

Output

Original Array 
10 20 30 40 50 
Enter the element to insert at end: 
65
Array After Inserting at end
10 20 30 40 50 65

Program Explanation

  1. Setup: The program starts by importing necessary utilities from the java.util package. It then creates a Scanner instance to read input from the console.
  2. Initial List Creation: An ArrayList of integers is initialized with a set of predefined values {10, 20, 30, 40, 50}.
  3. Display Original List: The program first prints “Original Array” and then iterates through the list, printing each value to show the initial state of the list.
  4. Input from User: The user is prompted to enter an integer to add to the end of the list. This value is captured using the Scanner and stored in elementToInsert.
  5. Appending Element: The captured integer is then added to the end of the list using the add method of ArrayList.
  6. Display Modified List: After insertion, the program prints “Array After Inserting at end” followed by the updated list to show how the list has changed post-insertion.

Program 3: Using Java Streams

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class InsertAtEnd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
        
        System.out.println("Original Array ");
        list.forEach(value -> System.out.print(value + " "));   
        System.out.println();
        
        System.out.println("Enter the element to insert at end: ");
        int elementToInsert = sc.nextInt();
        
        list.add(elementToInsert);

        int[] newArray = list.stream().mapToInt(Integer::intValue).toArray();

        System.out.println("Array after insertion at end:");
        for (int value : newArray) {
            System.out.print(value + " ");
        }

        sc.close();  
    }
}

Output

Original Array 
10 20 30 40 50 
Enter the element to insert at end: 
60
Array after insertion at end:
10 20 30 40 50 60

Program Explanation

  1. Initialization: It starts by creating a Scanner instance to read user input. An ArrayList of integers is initialized with predefined values {10, 20, 30, 40, 50}.
  2. Display Original List: The program prints “Original Array” followed by the elements of the list using a forEach loop with a lambda expression for clean and concise output.
  3. User Input for New Element: The user is prompted to enter an integer that they want to append to the end of the list. This integer is read from the console and stored in elementToInsert.
  4. Add Element to List: The integer entered by the user is added to the end of the ArrayList using the add method.
  5. Convert to Array and Display: The updated list is then converted into an array of integers (int[]) using streams. The ArrayList is streamed, mapped to integers, and collected into an array. The updated array is then printed, displaying all elements including the newly added one at the end.
  6. Resource Management: The Scanner object is closed at the end to free system resources associated with it.