Skip to content

add string to String array

To add a string to a string array in Java, you can use the Arrays.copyOf() method. Since Java arrays have a fixed size, this approach creates a new array that is one element larger and copies the original elements into it. Here's an example:


java
import java.util.Arrays;

String[] array = {"apple", "banana", "cherry"};
String str = "date";

int n = array.length;
String[] newArray = Arrays.copyOf(array, n + 1);
newArray[n] = str;

This will create a new string array called newArray that is one element larger than the array variable, and copy the elements of array into the new array. The new element, str, will be added to the end of the array.

Alternatively, you can use the ArrayList class to add a string to an array. ArrayList provides methods for adding and removing elements, so you can use it to create a dynamic collection that can grow and shrink as needed. Here's an example:


java
import java.util.Arrays;
import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
list.add(str);
String[] newArray = list.toArray(new String[0]);

This creates an ArrayList from the array variable using Arrays.asList(), adds the new element str using the add() method, and finally converts the list back to an array using toArray().

Dual-run preview — compare with live Symfony routes.