access array[i] outside of a method context; not possible?
This code compiles without error:
Code:
public class hello {
public static void main(String[] args){
int[] vector = new int[10];
vector[0]=3;
}
}
Whereas this code does not compile and generates several errors:
Code:
public class hello {
int[] vector = new int[10];
vector[0]=3;
public static void main(String[] args){
}
}
The errors i get are just like this one:
Code:
>./hello.java:3: error: ']' expected
>vector[0]=3;
> ^
So i feel tempted to conclude that an expression of the form array[i] outside of any method context is illegal?
Re: access array[i] outside of a method context; not possible?
oh i just remembered that with a static initialization block it would work:
Code:
public class hello {
static {
int[] vector = new int[10];
vector[0]=3;
}
public static void main(String[] args){
}
}
so i guess have to reformulate my question as outside of any static initialization block and outside of any method, in general are expressions like array[i]=x illegal?
Re: access array[i] outside of a method context; not possible?
Quote:
so i guess have to reformulate my question as outside of any static initialization block and outside of any method, in general are expressions like array[i]=x illegal?
Basically yes, although there are also instance initializer blocks which you can do this in. The only time you can assign values to an array outside a method or initializer is if you do it at declaration ie
Code:
String s = new String[]{"a", "b", "c"};
Re: access array[i] outside of a method context; not possible?
Quote:
Originally Posted by
keang
Basically yes, although there are also instance initializer blocks which you can do this in. The only time you can assign values to an array outside a method or initializer is if you do it at declaration ie
Code:
String s = new String[]{"a", "b", "c"};
thanks for confirmation!