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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 19541
    
  16

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: 18108
    
  39

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)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: nulllpointer exception in 2 dimensional string array
 
Similar Threads
where to define array and initialise
Cutting off a string after certain amount
how to write an El expression
How to get string portion of mixed content with JAXB?
Java NullpointerException while reading BufferedReader