zeymav zeymav - 3 months ago 17
Java Question

How can I add new item to the String array?


Possible Duplicate:

how to add new elements to a String[] array?




How can I add new item to the String array ? I am trying to add item to the initially empty String. Example :

String a [];

a.add("kk" );
a.add("pp");

Answer

From arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

enter image description here

So in case of String array once you create is with some length then you can't modify it. Like. But you can add element till its length.

String[] arr = new String[10]; // 10 is the length of array.
arr[0] = "kk";
arr[1] = "pp";
...

So if your requirement is to add many object its recommended to use List's Like :

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp"); 
Comments