πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Array in DSA (Java)  


Introduction
  • Arrays are linear data structures that store elements in a sequential/linear form.
  • Syntax :
    • int[] marks = {88, 74, 91, 82, 68, 94};
    • Arrays in DSA
  • We can access the array elements directly using their index position, making retrieval fast.
    For example:-
    • System.out.println(marks[0]); // Output: 88
      System.out.println(marks[2]); // Output: 91

Array Programs:-
  • Program 1:
    public class MainApp1
    {
        public static void main(String[] args)
        {
    
            // 1. Declare and create an array of size 6
            int[] marks = new int[6];
    
            // 2. Initialize array elements
            marks[0] = 88;
            marks[1] = 74;
            marks[2] = 91;
            marks[3] = 82;
            marks[4] = 68;
            marks[5] = 94;
    
            // 3. Access and print array elements using normal for loop (Way 1)
            System.out.print("Way 1: ");
            for (int i = 0; i < marks.length; i++)
            {
                System.out.print(marks[i] + " ");
            }
            System.out.println(); // Move to next line
    
            // 4. Access and print array elements using for-each loop (Way 2)
            System.out.print("Way 2: ");
            for (int no : marks)
            {
                System.out.print(no + " ");
            }
            System.out.println(); // Move to next line
        }
    }
    • Points to note:
      • We have accessed the array elements in 2 ways, i.e., using normal for loop and for-each loop. But for-each loop is preferred as it is simple and easy to understand.
      • Declaring and creating array like above is lengthy. We can also declare, create, and initialize the array in a single line using shorthand notation as shown in Program 2 below.
  • Program 2:
    public class MainApp2
    {
        public static void main(String[] args)
        {
            // 1. Declare and create an array using shorthand notation
            // This automatically initializes the array with the given values
            int[] marks = {88, 74, 91, 82, 68, 94};
    
            // 2. Access and print array elements using a for-each loop
            // The variable 'no' takes the value of each element sequentially
            System.out.print("Marks are: ");
            for (int no : marks)
            {
                System.out.print(no + " "); // Print each element
            }
        }
    }
    • Points to note:
      • In this program, we have declared, created, and initialized the array in a single line using shorthand notation.
      • We have accessed the array elements using for-each loop, which is the more preferred way.

Memory Management in Arrays

When we create arrays in Java, they are handled in memory in a specific way. Let's understand the key memory concepts behind arrays:

  1. Dynamic Memory Allocation:
    • In Java, arrays are not allocated at compile-time; they are allocated dynamically (at runtime) using the new keyword.
    • This means the size of an array must be specified at runtime, not during compilation.
    • Example:
      • int[] numbers = new int[3];
      • Here, memory for 3 integers is allocated when the statement is executed at runtime.
  2. Arrays are Objects and Stored in Heap Area:
    • In Java, arrays are objects, regardless of whether they hold primitive or non-primitive types.
    • Since objects are always stored in the heap memory, arrays are also stored in the heap.
    • The reference variable (like numbers in the below code) is stored in the stack memory, and it points to the array object in the heap.
    • Example:
      • int[] numbers = new int[3];
      • Here,
        • Actual array object (with 3 slots) β†’ stored in heap
        • numbers (reference) β†’
          • If the array is created as an instance variable, then the reference variable is also stored in the heap area (because instance variables are part of the object, and objects live in the heap).
          • If the array is created inside a method or block (local variable), then the reference variable is stored in the stack area.
  3. Arrays Store Data in Contiguous Memory Locations:
    • Arrays internally store elements in sequential (contiguous) memory locations for efficient access using indices.
    • But there are 2 different scenarios:
      • (a) Primitive Data in Arrays:
        • If an array holds primitive types (like int, char, double), the values are stored directly in contiguous memory blocks.
        • For example : int[] numbers = {10, 20, 30};
        • Primitive Arrays Memory Management
      • (b) Non-Primitive Data in Arrays
        • If an array holds objects (like String, Student, Employee), then the array stores only the reference (memory addresses) of those objects, not the actual objects themselves.
        • The actual objects are stored separately in the heap memory.
        • For example : String[] names = {"amit", "deepak", "rahul"};
        • Primitive Arrays Memory Management


Types of Arrays
  • There are mainly 2 types of Arrays :
    • Single-Dimensional Array
      • Stores elements in a single row.
      • Types of Single-Dimensional Array :
        • 1D Array int[] numbers = {10, 20, 30};
    • Multi-Dimensional Arrays
      • Arrays with more than one dimension (rows and columns).
      • Types of Multi-Dimensional Arrays:
        • 2D Array (most common)
          • Represents data in a table (rows Γ— columns).
          • int[][] matrix = {{1,2}, {3,4}};
        • Matrix Array
          • Usually refers to 2D arrays used for mathematical matrices.
          • Technically, it's a type of 2D array.
        • Jagged Array
          • A 2D array where each row can have a different number of columns.
          • int[][] jagged = {{1,2,3}, {4,5}, {6}};
        • Higher-Dimensional Arrays (3D, 4D, 5D …)
          • Rarely used, but possible in Java.