-
January 12th, 2012, 05:24 PM
#1
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?
-
January 12th, 2012, 05:34 PM
#2
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?
-
January 13th, 2012, 05:45 AM
#3
Re: access array[i] outside of a method context; not possible?
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"};
-
February 21st, 2012, 01:51 PM
#4
Re: access array[i] outside of a method context; not possible?
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!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|