I am using String Array declare as zoom z[]=new String[422];
. But this array stores value from 0
to 32
, so I got null pointer exception
after looping value 32
.
How to solve this problem in java?
How can I declare a dynamic array in java ?
Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.
First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.
You want to use a Set
or List
implementation (e.g. HashSet
, TreeSet
, etc, or ArrayList
, LinkedList
, etc..), since Java does not have dynamically sized arrays.
List<String> zoom = new ArrayList<>(); zoom.add("String 1"); zoom.add("String 2"); for (String z : zoom) { System.err.println(z); }
Edit: Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:
List<String> zoom = Arrays.asList("String 1", "String 2", "String n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With