Accessing Array Elements

  1. Key idea that you must remember when accessing array elements is:

    
        TYPE[] myArray = new TYPE[10];
    
    Then:
        myArray[i] is a variable of type TYPE    
    
    Example:
    
        int[] myArray1 = new int[10];          
        *** myArray1[i] is an int variable
    
        myArray1[i] = 1234;
    
        double[] myArray2 = new double[10];
        *** myArray1[i] is a double variable
    
        myArray1[i] = 1234;
    
        BankAccount[] myArray3 = new BankAccount[10];          
        *** myArray3[i] is an object reference variable   
    
        myArray1[i] = new BankAccount(1000);
        myArray1[i].withdraw(10);
        myArray1[i].deposit(10);
        System.out.println(myArray1[i].getBalance());
    
    

  2. Array objects in Java also has an array length instance variable:

    Example: use of the length variable in array
       int[] A = new int[...]; 
    
       int i;
       int sum = 0;
    
       for (i = 0; i < A.length; i++)    
          sum = sum + A[i];
    
    

  3. NOTE: don't confuse with length() to find length of a String

    Example: find length of a String
        String s = "Hello World";
    
        s.length()   - return length of string s !