Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays declaration

 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to do the array initialisation in a static block
 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you explain me clearly please?
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic