In this tutorial, I will show you the various approaches to adding elements to an array in Java.
The array is a collection of elements of the same data type and is regarded as a fixed-size data structure.
Because the array is unknown whether the location next to the last element of the array is available in memory, we cannot directly add elements to an array in Java.
In this tutorial, I will provide various Java source code and output methods for adding value to arrays.
Table Content
1. Add Value to an Array in Java
2. Add Element in String Type Array in Java
3. How to Add Elements to an Empty Array in Java
4. How to Add Elements to an Array in Java Dynamically
5. Add Elements to an Array in Java Dynamically with String Data Type
6. How to Add Element to Array in Java without Index
7. How to Add Element to Array in Java with Index
8. How to Add Elements in Array in Java using for loop?
9. Add Elements with String Data Type Array in Java using for loop
10. How to Add Element to Beginning of Array in Java
11. How to Add Element to ArrayList in Java
12. Add Multiple Elements in the ArrayList
13. Add the Elements in ArrayList with an Index Number
Add Value to an Array in Java
I used steps below to add a value to an array in Java:
Declare and initialize the array:
int[] myArray = { 1, 2, 3, 4 };
Decide the value's index and the value itself to be inserted:
int index = 2;
int value = 5;
Make a new array bigger than the previous array in size:
int[] newArray = new int[myArray.length + 1];
Up to the index where you wish to put the value, copy the elements from the first array into the new array:
for (int i = 0; i < index; i++)
{
newArray[i] = myArray[i];
}
Put the new value where you want it:
newArray[index] = value;
Add the last few elements from the initial array to the new array by copying them:
for (int i = index; i < myArray.length; i++)
{
newArray[i + 1] = myArray[i];
}
Assign the new array to the initial array variable to complete:
myArray = newArray;
The new value will now be added to the myArray array at the specified index.
Full Code,
import java.util.Arrays;
class Test
{
public static void main(String args[])
{
int[] myArray = { 1, 2, 3, 4 };
System.out.println("Orignal array value " +Arrays.toString(myArray));
int index = 2;
int value = 5;
int[] newArray = new int[myArray.length + 1];
for (int i = 0; i < index; i++)
{
newArray[i] = myArray[i];
}
newArray[index] = value;
for (int i = index; i < myArray.length; i++)
{
newArray[i + 1] = myArray[i];
}
myArray = newArray;
System.out.println("After add new value " +Arrays.toString(myArray));
}
}
Output:
In the output, you can see that we created a new array value of 5 at position 2.
Orignal array value [1, 2, 3, 4]
After add new value [1, 2, 5, 3, 4]
Add Element in String Type Array in JavaÂ
Here I used the previous method with an array of String types. I have updated the array's index 2 positions with a new value.
import java.util.Arrays;
class Test
{
public static void main(String args[])
{
String[] myArray = { "usa", "canada", "uk", "germany" };
System.out.println("Orignal array value " +Arrays.toString(myArray));
int index = 2;
String value = "australia";
String[] newArray = new String[myArray.length + 1];
for (int i = 0; i < index; i++)
{
newArray[i] = myArray[i];
}
newArray[index] = value;
for (int i = index; i < myArray.length; i++)
{
newArray[i + 1] = myArray[i];
}
myArray = newArray;
System.out.println("After add new value " +Arrays.toString(myArray));
}
}
Output:
View the output I updated the array with the new value "australia" at index position 2.
Orignal array value [usa, canada, uk, germany]
After add new value [usa, canada, australia, uk, germany]
How to Add Elements to an Empty Array in Java
We use the indexer to specify the element and the assignment operator to give it a value in order to add elements to an empty array.
In this example, I have first used the new keyword to create an empty array with a size of 5.
Then, by using the square bracket country name to assign values to specific indices, I added elements to the array.
Please note that an array's size cannot be modified after it is created.
Create a new array with a greater size and copy the elements from the existing array if you need to add more elements than the array's original capacity.
import java.util.Arrays;
class Test
{
public static void main(String args[])
{
// declare empty array
String str[] = new String[5];
// add value
str[0] = "United States";
str[1] = "Canada";
str[2] = "United Kingdom";
str[3] = "Australia";
str[4] = "Germany";
System.out.println("All Countries :");
System.out.println("");
for (String country : str)
{
System.out.println(country);
}
}
}
Output:
All Countries :
United States
Canada
United Kingdom
Australia
Germany
How to Add Elements to an Array in Java Dynamically
Using an ArrayList in Java, we can dynamically add elements to an array.Â
Similar to an array, an ArrayList is an ordered collection that enables the creation of resizable arrays of a single type.
When we add or remove elements from an array list, the list's capacity can be adjusted automatically. Dynamic arrays and ArrayList are synonyms.
The List interface, which extends the Collection interface, is implemented by the ArrayList class.
Here I illustrated how to use an ArrayList to dynamically add values to an array.
We must import the ArrayLists package before we can use it.
When we attempt to instantiate a new ArrayList in the absence of the package, the compiler will show an error.
import java.util.ArrayList;
I make an ArrayList object first with the necessary data type.
ArrayList<Integer> dynamicArray = new ArrayList<Integer>();
Then, I added 3 integer elements to the dynamic array using the add() method:
dynamicArray.add(10);
dynamicArray.add(20);
dynamicArray.add(30);
Then I used The toArray() method to convert the dynamic array into a regular array.
The toArray() function in Java allows us to change an ArrayList into an Array. The method accepts as an argument the name of the array we are converting from.
The array's type must match that of the ArrayList.
In this example, I used the size () method to find out how many elements are in the ArrayList. The process doesn't accept any input.
Integer[] regularArray = dynamicArray.toArray(new Integer[dynamicArray.size()]);
In the code above, an integer dynamic array is created, three elements are added, and then the array is changed to a regular array. This code can be changed to operate with arrays of other data types.
Full Code Snippet,
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<Integer> dynamicArray = new ArrayList<Integer>();
dynamicArray.add(10);
dynamicArray.add(20);
dynamicArray.add(30);
Integer[] regularArray = dynamicArray.toArray(new Integer[dynamicArray.size()]);
System.out.println(Arrays.toString(regularArray));
}
}
Output:
[10, 20, 30]
Add Elements to an Array in Java Dynamically with String Data Type
In the above example, the ArrayList object is created using the String data type.
Then, I added three string elements to the dynamic array using the add() method.
Then I used The toArray () method to convert the dynamic array into a regular array.
The code that follows first creates a dynamic array of strings and then expands it with three additional entries before changing its type to a regular array. This code can be changed to operate with arrays of other data types.
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<String> dynamicArray = new ArrayList<String>();
dynamicArray.add("united states");
dynamicArray.add("australia");
dynamicArray.add("germany");
String[] regularArray = dynamicArray.toArray(new String[dynamicArray.size()]);
System.out.println(Arrays.toString(regularArray));
}
}
Output:
[united states, australia, germany]
How to Add Element to Array in Java without Index
Java's java.util.ArrayList class can be used in place of a regular array if you want to add an element to an array without giving an index.Â
Here is a use case for an ArrayList:
Make a declaration for and create an ArrayList object:
ArrayList<String> myArrayList = new ArrayList<String>();
I used the add() method to add elements to the ArrayList.
myArrayList.add("united states");
myArrayList.add("australia");
The specified element is added to the end of the ArrayList using the add() method.
With the help of the get() method, I fetch elements from the ArrayList.
String element1 = myArrayList.get(0); // returns "united states"
String element2 = myArrayList.get(1); // returns "australia"
The element at the given index is returned by the get() method.
Keep in mind that objects of any class, not only strings, can be stored in an ArrayList. When declaring the ArrayList object, just swap String for the desired class name.
Full Code Snippet,
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add("united states");
myArrayList.add("australia");
String element1 = myArrayList.get(0); // returns "united states"
String element2 = myArrayList.get(1); // returns "australia"
System.out.println(element1);
System.out.println(element2);
}
}
Output:
united states
australia
How to Add Element to Array in Java with Index
The values may also be added using an index number. We use a comma to separate the index and value.
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add(0, "united states");
myArrayList.add(1, "australia");
myArrayList.add(2, "germany");
String element1 = myArrayList.get(0); // returns "united states"
String element2 = myArrayList.get(1); // returns "australia"
String element3 = myArrayList.get(2); // returns "germany"
System.out.println(element1);
System.out.println(element2);
System.out.println(element3);
}
}
Output:
united states
australia
germany
How to Add Elements in Array in Java using for loop?
You may use a for loop in Java to add elements to an array by performing the actions listed below:
Declare the necessary data type as an array and include its length.
Create a counter variable that starts at 0 and finishes at the length of the array minus 1 before beginning a for loop.
Ask the user for input or give each element of the array a value inside the loop by using the counter variable's index.
The array will have the desired values once the loop is finished.
Here I paste the sample code that expands an array of length three integers.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
int[] myArray = new int[3]; // declare and initialize the array
Scanner scanner = new Scanner(System.in); // create a scanner object for user input
for (int i = 0; i < myArray.length; i++) // initialize a for loop
{
System.out.print("Enter an integer: "); // prompt the user for input
myArray[i] = scanner.nextInt(); // assign the input to the current array element
}
System.out.println(Arrays.toString(myArray));
scanner.close(); // close the scanner to prevent resource leak
}
}
Compile Program:
First, I compiled the program with the javac Test.java command.
Then I ran the program with java Test command.
Here I entered below three integer numbers.
Enter an integer: 10
Enter an integer: 20
Enter an integer: 30
Output:
[10, 20, 30]
Add Elements with String Data Type Array in Java using for loop
I used the for loop in this example to add elements to an array of the String type.
Declare a string-type array and mention its size.
Create a counter variable that starts at 0 and finishes at the length of the array minus 1 before beginning a for loop.
Ask the user for input or give each element of the array a value inside the loop by using the counter variable's index.
The array will have the desired string values once the loop is finished.
Here is a sample of code that rises the value of three strings in an array of length 3.
A string can be given by the user to the nextLine() function of the Scanner class.
In the Java.util.Scanner class is defined. The text is read through to the end of the line using the nextLine() method. The cursor is moved to the following line after the line has been read.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
String[] myArray = new String[3]; // declare and initialize the array
Scanner scanner = new Scanner(System.in); // create a scanner object for user input
for (int i = 0; i < myArray.length; i++) // initialize a for loop
{
System.out.print("Enter an string: "); // prompt the user for input
myArray[i] = scanner.nextLine(); // assign the input to the current array element
}
System.out.println(Arrays.toString(myArray));
scanner.close(); // close the scanner to prevent resource leak
}
}
Compile Program:
First, compile the program with the javac Test.java command.
Then run the program with java Test command.
Here I entered below three strings elements.
Enter an string: united states
Enter an string: australia
Enter an string: germany
Output:
[united states, australia, germany]
How to Add Element to Beginning of Array in Java
Java requires that we perform the following steps in order to add an element to the beginning of an array:
Set the starting values for the declared array.
int[] originalArray = {1, 2, 3, 4, 5};
Create a variable and set its value to 0. The array will start out with the value of this variable.Â
// new element to be added to the beginning
int newElement = 0;
Make a brand-new array that is one size more than the first array.
// create a new array with a size one larger than the original array
int[] newArray = new int[originalArray.length + 1];
Beginning at index 1, copy every element from the original array to the new array.
// copy all the elements from the original array to the new array starting from index 1
System.arraycopy(originalArray, 0, newArray, 1, originalArray.length);
Add the new element at index 0 to the start of the new array.
// add the new element to the beginning of the new array at index 0
newArray[0] = newElement;
The new element is now at the start of the new array.
// the new array now contains the new element at the beginning
System.out.println(Arrays.toString(newArray));
Here is a sample of code that illustrates this:
import java.util.Arrays;
class Test
{
public static void main(String args[])
{
// original array
int[] originalArray = {1, 2, 3, 4, 5};
// new element to be added to the beginning
int newElement = 0;
// create a new array with a size one larger than the original array
int[] newArray = new int[originalArray.length + 1];
// copy all the elements from the original array to the new array starting from index 1
System.arraycopy(originalArray, 0, newArray, 1, originalArray.length);
// add the new element to the beginning of the new array at index 0
newArray[0] = newElement;
// the new array now contains the new element at the beginning
System.out.println(Arrays.toString(newArray));
}
}
Output:
The output of this code would be:
[0, 1, 2, 3, 4, 5]
How to Add Element to ArrayList in Java
Make an ArrayList object first, and then specify the kind of entries it should include.Â
You can use the following code to generate the ArrayList used in this example, which stores Strings:
ArrayList<String> myArrayList = new ArrayList<>();
Use the add() method and supply the element as a parameter to add an element to the ArrayList. Use the following code, for instance, to add the string "australia" to the ArrayList:
myArrayList.add("australia");
Code Snippet,
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<String> myArrayList = new ArrayList<>();
myArrayList.add("australia");
System.out.println(myArrayList);
}
}
Output:
[australia]
Add Multiple Elements in the ArrayList
The ArrayList can have multiple elements added by repeatedly using the add() method:
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<String> myArrayList = new ArrayList<>();
myArrayList.add("australia");
myArrayList.add("germany");
myArrayList.add("turkey");
System.out.println(myArrayList);
}
}
Output:
[australia, germany, turkey]
Add the Elements in ArrayList with an Index Number
The add(int index, E element) method allows you to add an element at a given location in the ArrayList, where the index specifies the position and the element to add.Â
Use the following code, for instance, to add the string "united kingdom" to the ArrayList at position 2:
myArrayList.add(2, "united kingdom");
Code Snippet,
import java.util.Arrays;
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
ArrayList<String> myArrayList = new ArrayList<>();
myArrayList.add(0, "australia");
myArrayList.add(1, "germany");
myArrayList.add(2, "united kingdom");
System.out.println(myArrayList);
}
}
Output:
[australia, germany, united kingdom]
No comments:
Post a Comment