• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

nulllpointer exception in 2 dimensional string array

 
utsav gupta
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I have a simple code which goes like

String[][] attr=new String[20][];
attr[0][0]="hi";
System.out.println("attr00"+attr[0][0]);

I am getting a nullpointer exception in the third line at runtime. Can you please explain.
Even if i remove the second line I still get the same thing.
Shouldnt hav the array elements be initilized with default values?

Thanks
Utsav.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that a 2 dimensional array is just an array of arrays and that the default value of an object is null.
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not getting the exception at the third line, but at the second line. Add this line just after creating the array and before the assignment and you'll see why:
 
utsav gupta
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Thanks for youe quick responses
So If I want assign the string "hi" at 0,0 location ,how do I do that?

 
Henry Wong
author
Marshal
Pie
Posts: 21427
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
utsav gupta wrote:
So If I want assign the string "hi" at 0,0 location ,how do I do that?



In order to assign an element to a certain location, that array location has to exist. Remember an two-dimensional array, is an array of arrays in java -- you never instantiated any of the arrays for the array of arrays.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic