0

I (think I) understand why I get a compile error (Illegal Start of Expression) at the tmpString = {"",...} line in this method (--> tmpString is immutable, though it does not have a problem with the tmpBase line before), but what is the cleanest way to fix this - perhaps another variable type? Thank you.

public static ArrayList<String> myMethod(String tmpWord, int tmpNum)
{
    ArrayList<String> tmpReturn = new ArrayList<String>(); 
    String   tmpBase   = tmpWord.substring(0,tmpWord.length()-2);
    String[] tmpString = {"a","a","g","g","ya"};
    switch(tmpNum)
    {
        case  1: tmpBase = "xx";
                 break;
        case  2: tmpBase = "yy";
                 break;
        case  3:
                 break;
        default:
        {
            tmpBase   = "-";
            tmpString = {"","","","",""};
            break;
        }
    }
    for (int j=0; j<5; j++)
        tmpReturn.add( (tmpBase + tmpString[j]) );
    return tmpReturn;
}
Mike
  • 23
  • 4
  • 8
    The compilation error has **nothing** to do with the immutability of Strings. Nothing. – Hovercraft Full Of Eels Oct 04 '16 at 12:22
  • Possible duplicate of [Array initialization syntax when not in a declaration](http://stackoverflow.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration) – xenteros Oct 04 '16 at 12:33

2 Answers2

16

It has nothing to do with immutability (arrays are NOT immutable). This syntax:

String[] array = { ... };

can only be used when an array variable is declared.

If you want to assign a new value to your array after it has been declared, you need to use:

tmpString = new String[] {"","","","",""};
assylias
  • 321,522
  • 82
  • 660
  • 783
  • ok, thank you for that. it compiles now, but the tmpBase does not change. Is the correction for this similar? I have been / am trying a few things – Mike Oct 04 '16 at 12:31
  • @Mike if your problem (which was compilation error) is solved, mark this answer as a solution. Now you can ask another question about your problem after trying to solve if on your own for a while. Please have a look at [ask]. – xenteros Oct 04 '16 at 12:32
  • @Mike Sounds like the perfect time to learn how to use a debugger and step through your code to see what happens. – assylias Oct 04 '16 at 12:35
  • assylias - i manually debug (so far) but will look into it. thanks – Mike Oct 04 '16 at 12:41
  • @Mike if you use an IDE, there must be a debug function somewhere which should be fairly easy to use and will allow you to see the code path and the value of your variables. If you don't use an IDE you can add some print statements but it's more cumbersome. – assylias Oct 04 '16 at 12:50
5

The direct array initializer is only available when declaring a variable. For later assignments, use a qualified initializer:

tmpString = new String[]{"", "", "", "", ""};
Peter Walser
  • 15,208
  • 4
  • 51
  • 78