| Author |
Arrays declaration
|
vatsalya rao
Ranch Hand
Joined: Feb 14, 2007
Posts: 63
|
|
I wrote a program about2 Dimensional arrays declaration like this. class array { static int [][] a1=new int[3][]; a1[0]=new int [2]; a1[1]=new int [2]; a1[2]=new int [2]; public static void main(String ar[]) { System.out.println("a1[0][1] is "+a1[0][1]); } } But iam getting the errors as ']' expected a[0]=new int[2]; ']' expected a[0]=new int[2]; ']' expected a[1]=new int[2]; ']' expected a[1]=new int[2]; ']' expected a[2]=new int[2]; ']' expected a[2]=new int[2]; where as if I change the program as below ie declarring array as non static and initializing in main() no errors.Can you explain me the reason please.Actually I tried to locate the error by myself but ... ended up posting here. class array { public static void main(String ar[]) { int [][] a1=new int[3][]; a1[0]=new int [2]; a1[1]=new int [2]; a1[2]=new int [2]; System.out.println("a1[0][0] is "+a1[0][0]); } } one more is ,If I declare the array as STATIC even in main too,besides the above mentioned errors Iam getting a few more like these: <identifier expected> System.out.println("a1[0][0] is "+a1[0][0]); illegal start of type System.out.println("a1[0][0] is "+a1[0][0]); class,interface,enum expected at line 21.I dont have 21st line in my program. can you please explain where Iam going wrong?
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
You need to do the array initialisation in a static block
|
Joanne
|
 |
vatsalya rao
Ranch Hand
Joined: Feb 14, 2007
Posts: 63
|
|
|
can you explain me clearly please?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
The only way to execute code outside of a method is by putting it in a separate block; this block can be static or not. So for instance: This code will be run in the following order: - static blocks, in order from top to bottom, when the class is loaded. - non-static blocks, in order from top to bottom, then the constructor when a new instance is created.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Arrays declaration
|
|
|