/**
 * Toy Examples to demonstrate how to use arrays of class types (String is the class type here)
 */
public class ArraysWithNulls {
  
  
  public static void main(String[] args) {
    
    //allocate array of 10 String variables
    //remember that the variable stores the ADDRESS of a string
    //Since none have been initialized, then they are all null (empty... cannot call a method on them)
    String[] strings = new String[10];
    //initialize all the even-indexed values to the String representation of their index (store i into array)
    for(int i = 0;i<strings.length;i=i+2){//NOT regular increment
      strings[i]=i+"";
    }
    
    //print each item
    for(int i = 0; i< strings.length; ++i){
     System.out.println(strings[i]);  //null will _print_ just fine
    }
    /*
     * Above prints:
     
     0 
     null 
     2 
     null 
     4 
     null 
     6 
     null 
     8 
     null
      
      
     */
    
    // ...but if you call a method on a null reference, you will get an exception (NullPointerException)
    for(int i = 0; i<strings.length;++i){
      //the following throws a java.lang.NullPointerException -- generally meaning you called a method
      //using a null object reference
      
      //System.out.println(" strings["+i+"].length() = "+strings[i].length() ); //  <- Crashes program
      
      //this works however:
      String s = strings[i]; //instead of putting strings[i] everywhere
      if(s == null) System.out.println("null, so not calling length()");
      else System.out.println(" strings["+i+"].length() = "+s.length() ); // now we know is valid String
    }
    
    /*Above prints:
     
      strings[0].length() = 1 
      null, so not calling length() 
      strings[2].length() = 1 
      null, so not calling length() 
      strings[4].length() = 1 
      null, so not calling length() 
      strings[6].length() = 1 
      null, so not calling length() 
      strings[8].length() = 1 
      null, so not calling length() 
     
     */
  }
  

  
}
