add string to String array
To add a string to a string array in Java, you can use the Arrays.copyOf()
method to create a new array that is one element larger than the original array, and then use a loop to copy the elements of the original array into the new array. Here's an example:
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. The ArrayList class provides methods for adding and removing elements, so you can use it to create a dynamic array that can grow and shrink as needed. Here's an example:
ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
list.add(str);
String[] newArray = list.toArray(new String[0]);
This will create an ArrayList from the array
variable using the Arrays.asList()
method, and then add the new element str
to the ArrayList using the add()
method. Finally, the toArray()
method is used to convert the ArrayList back to an array.