How to Add Value to an Array Java - onlyxcodes

Monday 1 May 2023

How to Add Value to an Array Java

The array is a collection of elements of the same data type and is regarded as a fixed-size data structure. 


Because it is unknown whether the location next to the last element of the array is available in memory, you cannot directly add elements to an array in Java. 


There are various approaches to adding elements to an array, though.


In this article, we'll go through how to add value to a Java array. 


The tutorial will also go through various Java source code and output methods for adding value to arrays. 


add value to array java

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

The steps below can be used 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 

We use the previous method with an array of String types. We update 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 We 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, we first use the new keyword to create an empty array with a size of 5. 


Then, by using the square bracket notation to assign values to specific indices, we add elements to the array.


It should be noted that an array's size cannot be modified after it is formed. 


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, you 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 is an illustration of 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 raise an error.


import java.util.ArrayList;

Make an ArrayList object first with the necessary data type:


ArrayList<Integer> dynamicArray = new ArrayList<Integer>();

Then, add 3 integer elements to the dynamic array using the add() method:


dynamicArray.add(10);
dynamicArray.add(20);
dynamicArray.add(30);

The toArray() method is then used 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 case, the size() method is utilized to find out how many elements are in the ArrayList. The process doesn't accept any input.


Java's size() function is available.


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, add three string elements to the dynamic array using the add() method.


The toArray() method is then used to convert the dynamic array into a regular array.


The code that follows first builds a dynamic array of strings, 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>();

Use 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, 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 is a sample of code that expands an array of length three with 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, compile the program with the javac Test.java command.


Then run the program with java Test command.


And enter three integer elements. 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

In this Java example, a for loop is used 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.


And enter three strings elements. 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 you 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]


Read Also:

What is Scope of Variables in Java?

What is a Class Variable and Method in Java?

How to Convert char to ASCII int in Java?

What is Array in Java with Example?

What is Bean in Java?

What are Variable Arguments in Java?

Context Switching in Java Thread Example

What is Long Array in Java?

What is Difference Between Array and ArrayList in Java?

What is Enterprise Application in Java?

Java Stream Iterate Example

What is Applet in Java with Example?

50 Best Java Basic Interview Questions for Fresher

What are the 4 types of loops in Java?

How to Run Package Program in Java using Command Prompt

What is final class and method in Java?

What is Encapsulation in Java with Realtime Example?

Java 8 Stream Min Max Example

Lambda Expressions in Java 8 Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Send Email after Registration with Activation Link in Java

How to Produce and Consume Restful Webservice in Java

Java MVC Login and Register Script using JSP & Servlet with MySQL

Java MVC Add, Edit, Delete using JSP and Servlet with MySQL

No comments:

Post a Comment

Post Bottom Ad