Why does this extraordinarily simple array assignment not work?
class Z
{
int[] ia=newint[3];
ia[0] = 3;
}
causes compiler error
C:\javatemp>javac Z.java
Z.java:5:']' expected
ia[0] = 3;
^
1 error
Please explain, somebody, thanks. (Uh, feel like a numbskull....).
Erm, I just half-figured it out...
This compiles without errors:
class ZZ
{
public static void main(String[] args)
{
int[] ia= new int[3];
ia[0] = 3;
}
}
Now, the question still is, why does Z.java not compile?
> Now, the question still is, why does Z.java not> compile?Because you can't just put anything inside a class body; only member declarations (fields, methods, constructors, nested types and initializers). "ia[0] = 3;" is neither of those.
Lokoa at 2007-7-9 5:35:44 >

> qUesT_foR_knOwLeDge
That's not particularly helpful.
It's something to do with making assignments to member variables (as in Z ia must be a member variable, whereas in ZZ it's a local variable) outside of a member function *I suppose*, but I don't know *exactly*.
Now, either you know, but are not willing to help, or you don't know, and can't help. Which is it?
Message was edited by:
JasonLind_
> > Now, the question still is, why does Z.java not
> > compile?
>
> Because you can't just put anything inside a class
> body; only member declarations (fields, methods,
> constructors, nested types and initializers). "ia[0]
> = 3;" is neither of those.
Thanks.
For anyone interested, I just discovered that the code in Z.java can be modified slightly to make it work, but putting the assignment in an instance initialization block:
class Z
{
int[] ia= new int[3];
{
ia[0] = 3;
}
}
The code now compiles without errors.