📚

Lecture 8: Arrays in Java

Jul 4, 2024

Lecture 8: Arrays in Java

Introduction to Arrays

  • Definition: Collection of data types (primitives or objects).
  • Need: Simplifies storing multiple elements without repetitive code.
  • Syntax: data_type[] array_name = new data_type[size]; // Example int[] rollNumbers = new int[5]; int[] rollNumbers2 = {23, 12, 45, 32, 15};
  • Rules:
    • All elements must be of the same type.
    • Declared with square brackets.

Memory Management

  • Stack and Heap memory.
  • Declaration happens in Stack; Initialization in Heap.
  • Dynamic memory allocation at runtime.
  • Continuous memory allocation not guaranteed in Java.
  • Indices start from 0.

Null and Default Values

  • Integers initialized to 0.
  • Strings and other objects to null.
  • null: Special literal, default for reference types, not primitives.

Operations on Arrays

Input/Output

  • Using loops to take input and display arrays.
  • Enhanced for loop (for-each) for simpler iteration. for (dataType item : array) { System.out.println(item); }
  • Arrays.toString() for printing arrays in a formatted manner.

Functions

  • Passing arrays to functions: Object reference is passed, changes in functions affect the original array. static void change(int[] arr) { arr[0] = 99; }

2D Arrays

  • Syntax: int[][] matrix = new int[rows][columns];
  • Internally: Array of arrays, not necessarily continuous memory.
  • Input and Output in 2D arrays involves nested loops. for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { arr[row][col] = sc.nextInt(); } }

ArrayList

  • Part of Collection Framework (java.util package).
  • Syntax: ArrayList<dataType> list = new ArrayList<>();
  • Dynamic size, non-primitive data types.
  • Methods: add, set, remove, contains, get.
  • How it works: Drops old array, copies to new larger array when needed.
  • Example: ArrayList<Integer> list = new ArrayList<>(); list.add(67); list.add(45); list.add(32); System.out.println(list.contains(67)); // true
  • Multi-dimensional ArrayLists possible (ArrayList of ArrayLists). ArrayList<ArrayList<Integer>> list = new ArrayList<>();

Practice Problems

  • Reverse an array using two-pointer technique. static void reverse(int[] arr) { int start = 0, end = arr.length - 1; while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } }
  • Find maximum element in an array and in a range. static int max(int[] arr) { int max = arr[0]; for (int i : arr) { if (i > max) max = i; } return max; }

Upcoming Topics

  • Sorting techniques.
  • More questions on arrays, searching, sorting.
  • Advanced topics like sliding window, two-pointer method.