• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array Question

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why should the above code give NullPointerexception ? Any ideas ?
-Sam
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI
you are defining a two dimensional array but you are not allocating it properly. When you say int[][]a = new int[1][] you have not allocated the array fully. After that you try to access the variable a[0][0]. Mind you the second dimension of array has not been allocated yet and hence it gives you NullPointerException.
 
sam pitt
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Anshul
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hello Sam,
Actually I guess
1. You should first learn the syntax before starting to write programs.
2. If you are not sure then check for the syntax every time.

I admit it is a good question. here is the answer.
int [][]a = new int[2][3]; means we are allocating 2 by 3 integer array and assigning it to 'a'. So this will have 2 rows and 3 columns. left index determines ROW and right index determines COLUMN.
The syntax for double-subscripted arrays, the one you used FOR THIS PROGRAM TO RUN int [][]a = new int[1][]; is meaning that
the double-subsripted array 'a' is having 1 row. But no columns.
So in the next line you got to specify the number of columns the row should have inorder to use it. you can do it by
a[0] = new int[1]; to allocate 1 column for the row a[0]
Then you can assign some value to it as you did.
a[0][0] = 12;
Here is the code:
public class MyClass{
public static void main(String args[]){
int[][]a = new int[1][];
a[0] = new int[1];
a[0][0] = 12;
System.out.println( a[0][0]);
}
}

This eliminates the runtime NullPointerException.
I guess this helps.
You can aswell refer to Complete Reference Java 2 or Deitel and Deitel for more understanding.
Thanks.
 
reply
    Bookmark Topic Watch Topic
  • New Topic