154

The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:

The array will be empty if the directory is empty or if no names were accepted by the filter.

How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ron Tuffin
  • 53,859
  • 24
  • 66
  • 78
  • 7
    I just realized this is a stupid question :( As these arrays are initialized exactly the same way as any other array just with a size 0. Shows how often I initialize arrays nowadays. I'll leave the question (not delete it) cause someday someone else might be just as stupid as I was just now :) – Ron Tuffin Nov 03 '09 at 07:57
  • 1
    I am confused about what use case you would have for an array of length 0, and why you wouldn't simply init to `null` in that special case. – Blake Mar 14 '18 at 18:46

7 Answers7

262

As others have said,

new String[0]

will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:

private static final String[] EMPTY_ARRAY = new String[0];

and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 8
    It seems that everybody likes typing: `private static final String[] EMPTY_ARRAY = {};` – Thomas Jung Nov 03 '09 at 08:29
  • 8
    @Thomas: I take your point, but for this particular case I prefer the more explicit form. It's clearer to me that it means "I want a string array with 0 elements" rather than "I want an array with this content - which is empty". Just personal preference I guess. – Jon Skeet Nov 03 '09 at 08:40
  • 2
    @Tony - I have to use the few places where Java can infer a type. :-) – Thomas Jung Nov 03 '09 at 08:48
  • This example not work for me (android == java) java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 –  May 14 '15 at 14:20
  • 1
    @delive: The example I've provided will still create an empty array, but because it's empty, you can't use `EMPTY_ARRAY[0]` - that's trying to access element 0, which doesn't exist... – Jon Skeet May 14 '15 at 14:22
  • @Jon Skeet, Yes, but also not work = new String[]{}; / = null; - > is normal because not is initialize :) or not have @references(maxorminindex) –  May 14 '15 at 15:12
  • @delive: I have *no* idea what you mean by that... `new String[] {} ` is *not* the same as null, and I don't know what you mean by `@references(maxorminindex)`. It sounds like you should ask a new question, making an effort to be clearer. – Jon Skeet May 14 '15 at 15:14
  • 1
    Looking at Apache Commons Lang, they have the following declaration in ArrayUtils: `public static final String[] EMPTY_STRING_ARRAY = new String[0];` – Jean-François Beauchef Jan 12 '17 at 19:44
  • If you realy want to use the same array on multiple places you can `private static final Object[] EMPTY_ARRAY = new Object[0];`and `public static T[] empty() { return (T[]) EMPTY_ARRAY; }` which you can use for any type. – Volker Seibt Dec 01 '17 at 12:31
  • @VolkerSeibt: No, that will throw an exception if you write (say) `String[] array = empty();` – Jon Skeet Dec 01 '17 at 13:16
  • @JonSkeet: You are right. I have overlooked that this usefull pattern does not apply to arrays. – Volker Seibt Dec 02 '17 at 16:54
  • @JonSkeet do you make the variable static to avoid its being created more than one time? That is, what if you were to use the variable only in one method of one class. Would you still make it `static` just to avoid creating it for every instance? – theyuv Mar 14 '18 at 16:22
  • @theyuv: Yes - it's not state that is different for each instance, so it's fine to be a static variable. – Jon Skeet Mar 14 '18 at 16:33
  • @JonSkeet hmm, maybe I'm getting off topic, but wouldn't this go against trying to give variables the shortest possible scope? I tried to ask this question here: https://stackoverflow.com/questions/49281872/should-immutable-final-variables-always-be-static and basically came away with the conclusion that if the variable isn't accessed outside of the method, then it shouldn't be static. – theyuv Mar 14 '18 at 16:38
  • @theyuv: If you want to only put it in the method, then sure - but that means you'll be creating a new instance every time you call the method, which is less efficient, given that you're fine to reuse the same array everywhere. – Jon Skeet Mar 14 '18 at 16:40
  • @JonSkeet Yes, I agree, but if I make every immutable, initialized, final variable static, isn't there a risk of this leading to unwieldy (ie: many static variables) code. – theyuv Mar 14 '18 at 16:43
  • @theyuv: Not in my experience, but YMMV. (I haven't seen examples where there are *that* many constants in use that aren't primitives.) – Jon Skeet Mar 14 '18 at 16:44
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166833/discussion-between-theyuv-and-jon-skeet). – theyuv Mar 14 '18 at 16:48
  • Or just `new String[]{};` – K. Stopa Feb 19 '21 at 16:27
26

String[] str = new String[0];?

mauris
  • 42,982
  • 15
  • 99
  • 131
19
String[] str = {};

But

return {};

won't work as the type information is missing.

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
15

Ok I actually found the answer but thought I would 'import' the question into SO anyway

String[] files = new String[0];
or
int[] files = new int[0];

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ron Tuffin
  • 53,859
  • 24
  • 66
  • 78
  • Add such commentary to your question...or select one of the answers which said the same thing. – Jonathan Leffler Nov 03 '09 at 08:12
  • 6
    Thanks for the comment Jonathan. As you might have noticed I posted this answer before anyone else (and as such there were no answers to select). I also don't see how adding the answer to the question makes for a better question. – Ron Tuffin Oct 06 '10 at 13:37
  • @Ron Tuffin -> asked Nov 3 '09 at 7:49:10Z -> answered Nov 3 '09 at 7:49:57Z It didn't even take you a minute to answer your own question? Really? :) – The incredible Jan Nov 24 '20 at 13:17
3

You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3

import org.apache.commons.lang3.ArrayUtils;

    class Scratch {
        public static void main(String[] args) {
            String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
        }
    }
freak0
  • 93
  • 6
1

Make a function which will not return null instead return an empty array you can go through below code to understand.

    public static String[] getJavaFileNameList(File inputDir) {
    String[] files = inputDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File current, String name) {
            return new File(current, name).isFile() && (name.endsWith("java"));
        }
    });

    return files == null ? new String[0] : files;
}
Swapnil Gangrade
  • 454
  • 6
  • 12
1

You can use following things-

1. String[] str = new String[0];
2. String[] str = ArrayUtils.EMPTY_STRING_ARRAY;<br>

Both are same.

dynamo
  • 89
  • 2
  • 9