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....).

[490 byte] By [JasonLind_a] at [2007-11-26 18:05:10]
# 1

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?

JasonLind_a at 2007-7-9 5:35:44 > top of Java-index,Java Essentials,New To Java...
# 2
You just told that you half-figured it?What did you figure out that made your program work?What changes did you have to make to your original program to make it work?If you can answer all these you have your answers.
qUesT_foR_knOwLeDgea at 2007-7-9 5:35:44 > top of Java-index,Java Essentials,New To Java...
# 3
> 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 > top of Java-index,Java Essentials,New To Java...
# 4

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

JasonLind_a at 2007-7-9 5:35:44 > top of Java-index,Java Essentials,New To Java...
# 5

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

JasonLind_a at 2007-7-9 5:35:44 > top of Java-index,Java Essentials,New To Java...
# 6

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.

JasonLind_a at 2007-7-9 5:35:44 > top of Java-index,Java Essentials,New To Java...
# 7
you are trying to assign a value into the array ouside of a method call. you cannot assign a value into the array in a declaration section.-- http://www.magiksafe.com
grilleda at 2007-7-9 5:35:44 > top of Java-index,Java Essentials,New To Java...