🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Arrays in Java  


Introduction
  • In Java, array is an object that stores a fixed number of elements of the same data type.
  • It stores multiple elements under a single variable name.
  • Syntax :
    • int[] marks = {88, 74, 91, 82, 68, 94};
    • Arrays in Java
  • Why we need arrays ?
    • Suppose we have 6 students and we want to store their marks:
      • int marks1 = 88;
        int marks2 = 74;
        int marks3 = 91;
        int marks4 = 82;
        int marks5 = 68;
        int marks6 = 94;
    • This works fine for a few students, but imagine we have 100 or 1000 students. Creating so many variables would be difficult and messy.
    • Solution: Arrays allow us to store all student's marks in a single variable:
      • int[] marks = {88, 74, 91, 82, 68, 94};
    • Now, we can access any student's mark using an index, loop through the marks, and perform calculations easily.

Key Features of Java Arrays:
  1. Index Based:
    • Arrays elements are accessed using indices starting from 0.
    • Example:
      • int[] numbers = {10, 20, 30};
        System.out.println(marks[0]); // Output: 10
        System.out.println(marks[2]); // Output: 30
  2. Fixed Size :
    • After creating an array, the size cannot be changed.
    • Example:
      • int[] numbers = new int[5]; // Size = 5
        // numbers[5] = 10; // ❌ Error, index out of bounds
  3. Stores Same Type of Elements:
    • Arrays always stored homogeneous elements i.e. same type of data.
    • Example:
      • int[] numbers = {10, 20, 30}; // Only int values allowed
        // numbers[0] = 5.5; // ❌ Error, cannot store double
  4. Contiguous Memory:
    • Array elements are stored in continuous memory locations, which allows fast access.
    • Diagram:
      • Arrays Stores Elements in Contegeous Memory Locations

Advantages of Arrays
  1. Efficient way to store multiple values:
    • Arrays allow storing multiple values of the same type in a single variable.
    • Example:
      • int[] marks = {88, 74, 91, 82, 68, 94};
        String[] names = {"Amit", "Bhupinder", "Deepak", "Kamal", "Rahul", "Ravi"};
  2. Versatile:
    • Arrays can store different types of data like numbers, characters or even objects.
    • Example:
      • int[] marks = {88, 74, 91, 82, 68, 94};
        String[] names = {"Amit", "Bhupinder", "Deepak", "Kamal", "Rahul", "Ravi"};
        Student[] std = {new Student(), new Student()};
  3. Easy to access elements using loop:
    • We can easily access all elements using loops like for or for-each.
    • Example using for loop:
      • for (int i = 0; i < marks.length; i++)
        {
            System.out.println(marks[i]);
        }
    • Example using for-each loop:
      • for (String name : names)
        {
            System.out.println(name);
        }
  4. Supports random access:
    • We can directly access any element using its index.
    • Example:
      • System.out.println(marks[2]); // Output: 91
        names[1] = "Harpreet";            // Changes "Bhupinder" to "Harpreet"
  5. Helps to Build Other Data Structures:
    • Arrays are the basic building blocks for many data structures like ArrayList, LinkedList, Stack, Queue, etc.
    • They provide a way to store and access elements efficiently, which these structures use internally.
  6. No Object Conversion / No Type Casting Needed:
    • When an array stores objects, you can directly access them without type casting.
    • This makes the code simpler and safer.
    • Example:
      • Person[] people = {new Person("Deepak"), new Person("Rahul")};
        
        // Directly access object methods without casting
        System.out.println(people[0].getName()); // Output: Deepak

Disadvantages of Arrays
  1. Fixed size - Less flexibility:
    • Once arrays are created, the size of an array cannot be changed.
    • Example:
      • int[] numbers = new int[5];
        // You cannot add a 6th element; need to create a new array
  2. Cannot store elements of different types:
    • All elements must be of the same data type.
    • Example:
      • int[] numbers = {10, 20, 30}; // Cannot add a string here
  3. Insertion or deletion in the middle is costly:
    • To insert or delete an element, other elements may need to be shifted.
    • Example (deleting an element):
      • int[] numbers = {10, 20, 30, 40};
        // To delete 20, shift 30 and 40 left
        numbers[1] = numbers[2]; // numbers becomes {10, 30, 30, 40}
        numbers[2] = numbers[3]; // numbers becomes {10, 30, 40, 40}
  4. Memory Wastage:
    • If we create an array larger than needed, the extra space is wasted because arrays have a fixed size.
    • Example:
      • int[] numbers = new int[10]; // Array can hold 10 elements
        numbers[0] = 5;
        numbers[1] = 10;
        // Only 2 elements are used, but memory for 10 is reserved
    • This can waste memory, especially if the array size is much larger than the number of elements you actually store.
  5. No Built-in Methods:
    • Arrays in Java do not have built-in methods for operations like adding, removing, or searching elements.
    • We have to write our own code to perform these operations.

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.

Points to Remember:
  1. Index starts from 0
    • The first element of an array is at index 0.
    • int[] marks = {88, 74, 91, 82, 68, 94};
      System.out.println(marks[0]); // Output: 88
  2. No of elements in an array = array.length
    • We can calculate the number of elements in an array using length property.
    • int[] marks = {88, 74, 91, 82, 68, 94};
      System.out.println(marks.length); // Output: 6
  3. Last index = array.length - 1
    • The last element’s index is always one less than the array size.
    • int[] marks = {88, 74, 91, 82, 68, 94};
      System.out.println("Last index position : "+marks.length - 1); // Output: 5
      System.out.println("Last Element : "+marks[marks.length - 1]); // Output: 94
  4. Can store primitives or objects
    • Arrays can hold primitive types like int, char, etc., or objects like String or custom classes.
    • char[] letters = {'A', 'B', 'C'};
      String[] names = {"Deepak", "Rahul", "Kamal"};
      Person[] people = {new Person(), new Person()};