-1

About nested for loop of 2D array, why it should be ( int i=0; i<cars.length; i++), not ( int i=0; i<=cars.length; i++) ?

public class Main {

public static void main(String[] args) {
        
    // 2D array = an array of arrays
    
    String[][] cars =   {   
                            {"Camaro","Corvette","Silverado"},
                            {"Mustang","Ranger","F-150"},
                            {"Ferrari","Lambo","Tesla"}
                        };
    
    /*
    cars[0][0] = "Camaro";
    cars[0][1] = "Corvette";
    cars[0][2] = "Silverado";
    cars[1][0] = "Mustang";
    cars[1][1] = "Ranger";
    cars[1][2] = "F-150";
    cars[2][0] = "Ferrari";
    cars[2][1] = "Lambo";
    cars[2][2] = "Tesla";
    */
    
    for(int i=0; i<cars.length; i++) {
        System.out.println();
        for(int j=0; j<cars[i].length; j++) {
            System.out.print(cars[i][j]+" ");
        }
    }
}

}

aya2222
  • 27
  • 3

1 Answers1

0

In Java and most other programming languages the first element is at position 0. Thus if myArray is defined as myArray[10] it will have a length of 10 and index positions 0 through 9. Thus myArray[10] = I would give you an array out of bounds error.

DCR
  • 14,737
  • 12
  • 52
  • 115