-2

I initialise a global array of Strings like so:

    private static final String[] foods = new String[]{"Pasta", "Beef", "Soup", "Chicken"};

And I use foods[0] in a switch statement. Says it requires a constant expression. What is not constant about this?

  • You can write `foods[0] = null;`. It's simply not a constant. – Andy Turner Apr 22 '18 at 18:08
  • can you show us your switch statement please? – YCF_L Apr 22 '18 at 18:08
  • Possible duplicate of [Java switch statement: Constant expression required, but it IS constant](https://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant) – zython Apr 22 '18 at 18:09

1 Answers1

3

The reference to the array, foods, is constant, but you could easily have written, somewhere in your program:

foods[0] = "abc";

Thus foods[0] is not a constant.

Jim Garrison
  • 83,534
  • 20
  • 149
  • 186
  • I would mention that constant expressions are enumerated in https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.28 – Andy Turner Apr 22 '18 at 18:11
  • Okay - how do I fix it / what do I need to understand to be able to fix it? – Edwin Carlsson Apr 22 '18 at 18:11
  • @Edwin show us the switch. You can probably do it without the switch. Or, define the array elements using constants, and reference the constant in the switch. – Andy Turner Apr 22 '18 at 18:13