12

What does the default "" part mean in the following code?

public @interface MyAnnotation {
    String[] names() default "";
}

Is it equal to

String[] names() default new String[0];

?

Redtama
  • 1,603
  • 1
  • 18
  • 35
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

2 Answers2

19
public @interface MyAnnotation {
    String[] names() default "";
}

means that by default names will be an array of one empty String ("").

This is the same as if you've used the array-initializer:

public @interface MyAnnotation {
    String[] names() default { "" };
}

Additionally, String[] names() default new String[0]; doesn't compile, because the (default) value of an annotation property must be a constant expression.

As a homework, you can annotate something with MyAnnotation and explore its properties with Reflection.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
3

It is equivalent to an array with a single element consisting of the empty string. From the Java Language Specification section 9.7.1 on annotations:

If the element type is an array type, then it is not required to use curly braces to specify the element value of the element-value pair. If the element value is not an ElementValueArrayInitializer, then an array value whose sole element is the element value is associated with the element. If the element value is an ElementValueArrayInitializer, then the array value represented by the ElementValueArrayInitializer is associated with the element.

M A
  • 71,713
  • 13
  • 134
  • 174