This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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: 19651
    
  18

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: 18509
    
  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)
 
Don't get me started about those stupid light bulbs.
 
subject: nulllpointer exception in 2 dimensional string array
 
Similar Threads
How to get string portion of mixed content with JAXB?
Cutting off a string after certain amount
where to define array and initialise
Java NullpointerException while reading BufferedReader
how to write an El expression