-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?

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
  • 85,615
  • 20
  • 155
  • 190
  • 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