aspose file tools*
The moose likes Beginning Java and the fly likes nulllpointer exception in 2 dimensional string array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "nulllpointer exception in 2 dimensional string array" Watch "nulllpointer exception in 2 dimensional string array" New topic
Author

nulllpointer exception in 2 dimensional string array

utsav gupta
Ranch Hand

Joined: Mar 19, 2009
Posts: 57
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

Joined: Oct 25, 2008
Posts: 2700

Remember that a 2 dimensional array is just an array of arrays and that the default value of an object is null.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
utsav gupta
Ranch Hand

Joined: Mar 19, 2009
Posts: 57
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
Sheriff

Joined: Sep 28, 2004
Posts: 18997
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: nulllpointer exception in 2 dimensional string array