Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare string array[] of unknown size (JAVA)

I want my String[] array; to be static but I still don't know it's size.

Is there any way to declare string array of unknown size? As much as possible I don't want to use ArrayList

like image 455
tin Avatar asked Aug 30 '16 11:08

tin


People also ask

Can we declare String array without size in Java?

There are two ways to declare string array - declaration without size and declare with size. There are two ways to initialize string array - at the time of declaration, populating values after declaration. We can do different kind of processing on string array such as iteration, sorting, searching etc.


2 Answers

You don't need to know the array size when you declare it

String[] myArray;

but you do need to know the size when you initialize it (because Java Virtual Machine needs to reserve a continuous chunk of memory for an array upfront):

myArray = new String[256];

If you don't know what the size will need to be in the moment you initialize it, you need a List<String>, or you'll be forced to make your own implementation of it (which is almost certainly worse option).

like image 52
Jiri Tousek Avatar answered Sep 19 '22 19:09

Jiri Tousek


No, it needs to be declared, and thus have a length before you can set elements in it.

If you want to resize an array, you'll have to do something like: Expanding an Array?

like image 27
steveman Avatar answered Sep 20 '22 19:09

steveman