Lecture 8: Arrays

Jul 11, 2024

Lecture 8: Arrays

Introduction to Arrays

  • What is an array?
    • A collection of data types (primitives or objects)
    • Syntax: dataType[] indicating an array
  • Why Arrays?
    • Efficient data storage and management
    • Example: Storing multiple roll numbers
  • Syntax
    • Declaration: dataType[] arrayName;
    • Initialization: arrayName = new dataType[size]; or dataType[] arrayName = {value1, value2, ...};

Key Points

  • Data in arrays must be of the same type
  • Declaration and initialization
    • Declaration assigns reference variable
    • Initialization creates the actual object in heap memory
  • Dynamic Memory Allocation
    • Memory allocated at runtime
    • Java uses a new keyword for creating objects
    • Example: int[] rollNumbers = new int[5];

Memory Management

  • Arrays stored in heap memory
  • Objects in heap memory are not necessarily continuous
  • Primitives stored in stack, objects in heap
  • Array Indices
    • Arrays start at index 0
    • Example: arr[0] accesses the first element

Null Value

  • By default, array elements of objects are initialized to null
  • null is a special literal value

Input and Output of Arrays

  • Input elements using loops
    • Example: Using Scanner for taking input
  • Output elements
    • Using loops for printing
    • Using Arrays.toString() for easy printing

Enhanced For Loop

  • Syntax:
    for(dataType element : arrayName) { 
      // code 
    }
    

Multi-Dimensional Arrays (2D Arrays)

  • Definition and Initialization
    • Example: int[][] arr = new int[3][4];
    • Input using nested loops
    • Variable number of columns allowed
  • Internal Representation
    • Arrays of arrays stored in heap memory

ArrayList

  • Dynamic arrays that allow dynamic resizing
  • Syntax:
    ArrayList<dataType> list = new ArrayList<>();
    
  • Supports various operations: add, set, remove, contains
  • Internally handled using copying and doubling the size of the array

Questions and Examples

  • Swapping elements in an array
  • Finding the maximum element in an array or a range
  • Reversing an array
    • Using two-pointer method
  • More complex problems and methods like rotation, Armstrong number, palindrome

Plan for Next Sessions

  • Sorting techniques
  • Detailed questions on arrays
  • Searching techniques and related questions
  • Advanced patterns: Sliding window, two-pointer method

Conclusion

  • Comprehensive understanding of arrays
  • Importance of practice and applying concepts