Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array declaration

 
vijay gardiner
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've a pgm like :
class Example {
public static void main(String args[]) {
int a[][] = new int[5][5];
a[0][] = {1,2,3,4,5};
for (int i=0,j=0;i<5;++i,++j)
System.out.println(a[i][j]);
}
}
when i compile I get an illegal start of expression.....why is that?
I've declared int a[][] = new int [5][5]; (a 2 dimensional array)
then i've initialised the first row of the array as {1,2,3,4,5}, i don't understand why there is any error in the above statment.
Could anyone please clarify.
Thanx,
Vijay
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vijay
When you create an array you can either use the form new int a[] = new int[5]
or the form
a[] = {1,2,3,4,5};
The first form explicitly creates an array of ints that has five elements. The second way implicitly does the same thing. The problem with your example is that your trying to recreate the same array. Once you've declared the size of the array the only way to get data into it is to specifically access each element and put a value into it.
hope that helps
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This works.
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vijay g,
Please read http://www.javaranch.com/name.jsp and edit your profile to change your display name. Thanks.
 
Erik Dark
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry Marilyn can't get your code working.
This is my suggestion to populate and (optionally) print it:

Erik Dark
[ January 28, 2002: Message edited by: Erik Dark ]
[ January 28, 2002: Message edited by: Erik Dark ]
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hmmmm. When I run this I get:

1
java.lang.NullPointerException
at Example1.main(Example1.java:9)
Exception in thread "main"

********* reason ********

When i=0 and j=0, the output is one
After i is incremented to 1 and j is incremented to 1, since anything after a[0] is undefined (due to the empty bracket in the declaration -- new int[5][] ), you get a NullPointerException.

Now if you created the array as:
int a[][] = new int[5][5];
you would no longer get an exception because all the elements would be initialized (to zeros).

The point I was making is that you no longer get an illegal start of expression if you declare the array correctly.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic