Friday, October 30, 2009

Published 10/30/2009 by with 7 comments

illegal initializer

You may see this error for writing wrong expression to initialize an array. See the code below:

int data={42,15,27,20,19};

If you compile this, you will see the following error message:

illegal initializer for int
int data={42,15,27,20,19};
^

Here the array is not declared properly as we have not put [ ] for declaring the array. The correct code is:

int data[ ]={42,15,27,20,19};

or

int[ ] data={42,15,27,20,19};
    email this       edit

7 comments:

  1. What about String[] x = {{"NewDelhi","Rs"},
    {"Islamabad","Rs"},
    {"London","Euro"},
    {"Washington","Dollar"}};

    It is also producing same error. . .
    Reason. . . ????

    ReplyDelete
  2. Here two dimensional String values are assigned to one dimensional array.

    Correct code will be:

    String[][] x = {{"NewDelhi","Rs"},
    {"Islamabad","Rs"},
    {"London","Euro"},
    {"Washington","Dollar"}};

    ReplyDelete
  3. ~/workspace/java/ $ javac TestArray.java
    TestArray.java:11: error: illegal initializer for int
    for (int i = {2,4,6,8,10}; i == myList.length; i++) {
    ^
    1 error

    ReplyDelete
    Replies
    1. Correct code would be:
      for(int i = 0; i<myList.length; i++)

      Delete