Java Program to insert element to an array
Program
import java.util.Scanner;
public class InsertElementsToArray {
public static void main(String[] args) {
int newElement;
int i;
System.out.println("Enter the required size of the array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
int inputArray[] = new int [size+1];
System.out.println("Enter the elements of the array: ");
for(i=0; i<size; i++){
inputArray[i] = reader.nextInt();
}
System.out.print("Enter the element which you want to insert: ");
newElement = reader.nextInt();
inputArray[size] = newElement;
System.out.print("Printing array elements after inserting : ");
for(i = 0; i < size; i++) {
System.out.print(inputArray[i]+",");
}
System.out.print(inputArray[size]);
}
}
This Java program demonstrates how to insert an element into an array.
-
Input Array Size and Elements:
- The user is prompted to input the size of the array (
size
) using aScanner
object. - An integer array
inputArray[]
is created with a size ofsize + 1
to accommodate the new element. - The user enters the array elements, which are stored in the first
size
positions ofinputArray
.
- The user is prompted to input the size of the array (
-
Insert New Element:
- The user is prompted to input the new element to be inserted.
- The new element is stored at the last position of the array (
inputArray[size]
).
-
Display Array:
- A
for
loop is used to print the array elements, including the newly inserted element.
- A
Key Points:
- Array Size:
- The array is initialized with one extra position to allow insertion of a new element without overwriting existing data.
- Limitations:
- The program does not allow insertion at a specific index. To achieve that, additional logic would be required to shift elements.
- Static Array:
- The size of the array is fixed after creation, demonstrating a simple approach to array manipulation without using dynamic data structures like
ArrayList
.
- The size of the array is fixed after creation, demonstrating a simple approach to array manipulation without using dynamic data structures like
Output
javac .\InsertElementsToArray.java
java InsertElementsToArray
Enter the required size of the array:
3
Enter the elements of the array:
11
22
33
Enter the element which you want to insert: 44
Printing array elements after inserting : 11,22,33,44