Add Elements to Array in Java

Add elements to array in java. In a given Array, a Java program to add an element in a specific position. Enter the array’s size, followed by all of the array’s elements. Now type in the element you want to insert and the location where you want it to go. We shift all the elements in the array by one to make it easier to insert the element.

 import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, pos, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array");
n = s.nextInt();
int a[] = new int[n+1];
System.out.println("Enter all the elements");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the position where you want to add the element");
pos = s.nextInt();
System.out.print("Enter the element you want to add");
x = s.nextInt();
for(int i = (n-1); i >= (pos-1); i--)
{
a[i+1] = a[i];
}
a[pos-1] = x;
System.out.print("After adding the element");
for(int i = 0; i < n; i++)
{
System.out.print(a[i]+",");
}
System.out.print(a[n]);
}
}

 

Output:

Enter no. of elements you want in array5
Enter all the elements
23
45
67
78
55
Enter the position where you want to add the element3
Enter the element you want to add100
After adding the element23,45,100,67,78,55

Array Method in Java Program

In Java, an array is a collection of variables that are referred to by a single variable name and an index number. An array’s items are all elements. An array’s items must all be of the same type. An int array, for example, may store int values, whereas a String array can include strings.

For Loop to Execute Add Elements to Array in Java

The “for” loop in Java is an entry-controlled loop that allows a user to iteratively run a block of statement(s) for a defined number of times. The number of iterations is determined by the test condition specified within the “for” loop. The Java “for” loop is one of the simplest Java loops to grasp.

A “For” Loop is used to iterate over a specified block of code a predetermined number of times. A for-loop (or simply for loop) is a control flow statement in computer science that specifies iteration and allows code to be performed repeatedly. The term for-loop is derived from the word for, which is used as the keyword to initiate a for-loop in various programming languages.