To add a string to an array in Java, you can use the add
method of the ArrayList
class or the Arrays.copyOf
method to create a new array and copy the elements.
Here's an example of how you could use the add
method of the ArrayList
class to add a string to an array:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("hello"); list.add("world"); String[] words = list.toArray(new String[0]); System.out.println(Arrays.toString(words)); } }S:ecruowww.lautturi.com
In this example, the ArrayList
object named list
is initialized with no elements. The add
method is then used to add two strings to the list
. The toArray
method is used to convert the list
to an array of strings, and the result is assigned to the words
variable. Finally, the Arrays.toString
method is used to print the words
array as a string.
The output of this example would be the following array:
[hello, world]
Keep in mind that the ArrayList
class is part of the java.util
package, which is included in the standard Java SE library. You can use a similar approach to add other types of objects to an array, by replacing the generic type String
with the appropriate type.
Alternatively, you can use the Arrays.copyOf
method to create a new array and copy the elements manually. Here's an example of how you could use the Arrays.copyOf
method to add a string to an array:
import java.util.Arrays; public class Main { public static void main(String[] args) { String[] words = new String[] {"hello"}; words = Arrays.copyOf(words, words.length + 1); words[words.length - 1] = "world"; System.out.println(Arrays.toString(words)); } }
In this example, the words
array is initialized with a single element using an array literal. The Arrays.copyOf
method is then used to create a new array with a length one element longer than the original array, and the result is assigned to the words
variable.