📊

Understanding 2D Arrays in Java

May 7, 2025

Lecture Notes: 2D Arrays in Java

Introduction to 2D Arrays

  • Definition: A two-dimensional array in Java is an array where each element is itself an array.
  • Use: Useful for storing a matrix of data.

One-Dimensional Arrays Example

  • String Arrays:
    • Fruits: apple, orange, banana
    • Vegetables: potato, onion, carrot
    • Meats: chicken, pork, beef, fish

Creating a Two-Dimensional Array

  • Declaration: Use two sets of square brackets [][].
  • Example:
    • Name: groceries
    • Structure: Each element (fruits, vegetables, meats) is an array.

Displaying Elements of a 2D Array

  • For Loop: Use a loop to iterate through each element.
    • Each element is a string array.
    • Print each array to show memory addresses initially (because arrays are reference types).
  • Nested Loop: To access individual elements within these arrays.
    • Inner elements are strings.
    • Use println for new lines.

Modifying 2D Arrays

  • Access/Modify Elements: Use two indices [row][column].
    • Example modifications:
      • Change apple to pineapple: groceries[0][0] = "pineapple"
      • Change potato to celery: groceries[1][0] = "celery"
      • Change pork to eggs: groceries[2][1] = "eggs"

Mini Project: Phone Number Pad

  • 2D Array of Characters
    • Declaration: char[][] telephone
    • Structure:
      • Row 1: 1 2 3
      • Row 2: 4 5 6
      • Row 3: 7 8 9
      • Row 4: * 0 #
  • Display with Nested Loops
    • Outer loop iterates through rows (arrays of characters).
    • Inner loop iterates through characters in each row.*

Conclusion

  • Summary: 2D arrays are arrays where each element is an array, useful for matrix-like data.
  • Usage: Even though not used frequently, understanding them is essential.