public class TestDogs {
    public static void main(String [] args) {
        Dog [][] theDogs = new Dog[3][];
        System.out.println(theDogs[2][0].toString());
    }
}
class Dog{ }
            Asked
            
        
        
            Active
            
        
            Viewed 75 times
        
    0
            
            
         
    
    
        Madhawa Priyashantha
        
- 9,633
- 7
- 33
- 60
- 
                    [2D arrays](http://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm) – Greg Kopff Jun 09 '15 at 06:26
2 Answers
3
            theDogs[2] array is null, since you didn't initialize it. Even it you initialized it, theDogs[2][0] would still be null, so calling toString on it would still throw NullPointerException.
Example how to initialize the array and the Dog instance :
Dog [][] theDogs = new Dog[3][];
theDogs[2] = new Dog[7]; // initialize the 3rd row of theDogs 2D array
theDogs[2][0] = new Dog (); // initialize the Dog instance at the 1st column of the 3rd row
System.out.println(theDogs[2][0].toString()); // now you can execute methods of theDogs[2][0]
 
    
    
        Eran
        
- 387,369
- 54
- 702
- 768
- 
                    How is "Dog [][] theDogs = new Dog[3][];" different from "Dog theDogs = new Dog();"? – Jun 09 '15 at 07:50
- 
                    @arjunhegde The first initializes an array that can contain Dog[] references (i.e. arrays of Dog). Each element in the array is initialized to null. The second creates a single instance of the Dog class. – Eran Jun 09 '15 at 07:52
0
            
            
        new Dog[3][]; creates a new array to hold Dog[] instances. You will have to add Dog[] instances to it. 
theDogs[2][0] will give you NPE. Actually, theDogs[2] is not initialized, so this will give you NPE even before you proceed to theDogs[2][0]. 
 
    
    
        TheLostMind
        
- 35,966
- 12
- 68
- 104
- 
                    No, `new Dog[3][]` creates a new array to hold references to `Dog[]` instances (i.e. arrays). It's `theDogs[2]` which is null here - it doesn't get as far as a null `Dog` reference. – Jon Skeet Jun 09 '15 at 06:27
- 
                    How is "Dog [][] theDogs = new Dog[3][];" different from "Dog theDogs = new Dog();"? – Jun 09 '15 at 07:49