CS102 - Java Programming: Arrays

Arrays Basics

  • Arrays are Java objects for organizing large amounts of information.
  • Focus topics:
    • Declaration and usage
    • Bounds checking and capacity
    • Stores object references
    • Variable length parameter lists

Key Concepts

  • Array Declaration:

    • Syntax: type[] arrayName = new type[size];
    • Example: int[] scores = new int[10];
    • Size determined during declaration; cannot change.
  • Using Arrays:

    • Access elements: arrayName[index] (0-based indexing).
    • Example: scores[2] refers to the 3rd value.
    • Can modify values, iterate using loops (for-each).
  • Bounds Checking:

    • Java checks if index is valid (0 to N-1).
    • Out-of-bounds access throws ArrayIndexOutOfBoundsException.
  • Array Length:

    • Accessed via: arrayName.length.
    • Represents number of elements, not the largest index.
  • Initializer Lists:

    • Declare and initialize in one step:
    • Example: int[] units = {147, 323, 89};
  • Passing Arrays as Parameters:

    • Pass entire array or single elements.
    • Changed elements inside methods reflect in the original array.

Examples

  1. Basic Array Operations:

    • Declare: int[] list = new int[15];
    • Initialize: for (int index = 0; index < LIMIT; index++) { list[index] = index * MULTIPLE; }
    • Print: for (int value : list) { System.out.print(value + " "); }
  2. Bounds Checking Example:

    • Accessing an index greater than or equal to length causes an error.
  3. Using Initializer Lists:

    • int[] primeNums = {2, 3, 5, 7, 11};
    • Length: primeNums.length returns 5.

Conclusion

  • Understanding arrays is fundamental for data organization in programming.
  • Practice with bounds checking and execution of array methods for better coding proficiency.