Add Element to Array in Java

This article shows how to Add an element to an Array in a Java program. Since arrays in Java have a fixed size, adding a new element typically involves creating a larger array, copying the existing elements into it, and then appending the new element. Alternatively, you can use dynamic data structures like ArrayList for easier element addition.

Add Element Using a New Array

This program creates a larger array, copies existing elements into it, and appends the new element at the end.

package com.javacodepoint.array;

public class AddElement {
	public static void main(String[] args) {
		int[] arr = { 10, 20, 30, 40, 50 };
		int element = 60; // Element to be added

		// Create a new array of size n+1
		int[] newArr = new int[arr.length + 1];

		// Copy elements to the new array
		for (int i = 0; i < arr.length; i++) {
			newArr[i] = arr[i];
		}

		// Add the new element at the end
		newArr[arr.length] = element;

		// Print the new array
		System.out.println("Array after adding an element:");
		for (int num : newArr) {
			System.out.print(num + " ");
		}
	}
}

Add Element Using ArrayList

This program leverages Java’s ArrayList to dynamically add an element without manually resizing or copying data.

package com.javacodepoint.array;

import java.util.ArrayList;

public class AddElementUsingArrayList {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>();
		list.add(10);
		list.add(20);
		list.add(30);
		list.add(40);
		list.add(50);

		// Add the new element
		list.add(60);

		// Print the updated list
		System.out.println("ArrayList after adding an element: " + list);
	}
}

Notes:

  • Use the first approach if you need a fixed-size array.
  • Use ArrayList for dynamic resizing and easier manipulation.

For a detailed guide on inserting an element at a specific position in an array, check out our article: Insert Element at Specific Position in Array.

Java logical programs list


Java Basic Programs

Java String Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *