Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA- how to assign string value to string array dynamically

Tags:

java

In my application i got string values dynamically. I want to assign these values to string array then print those values.But it shows an error(Null pointer exception) EX:

String[] content = null;
for (int s = 0; s < lst.getLength(); s++) {
    String st1 = null;
    org.w3c.dom.Node nd = lst.item(s);
    if (nd.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
        NamedNodeMap nnm = nd.getAttributes();

        for (int i = 0; i < 1; i++) {
            st1 = ((org.w3c.dom.Node) nnm.item(i)).getNodeValue().toString();
        }
    }

    content[s] = st1;
    //HERE it shows null pointer Exception.
}  

Thanks

like image 737
user735855 Avatar asked Feb 24 '23 03:02

user735855


1 Answers

This is because your string array is null. String[] content=null;

You declare your array as null and then try to assign values in it and that's why it is showing NPE.

You can try giving initial size to your string array or better to use ArrayList<String>. ie:

String[] content = new String[10]; //--- You must know the size or array out of bound will be thrown.

Better if you use arrayList like

List<String> content = new ArrayList<String>(); //-- no need worry about size.

For list use add(value) method to add new values in list and use foreach loop to print the content of list.

like image 179
Harry Joy Avatar answered Feb 26 '23 21:02

Harry Joy