SrcForge

Lesson 16

Arrays

Arrays store multiple values of the same data type in a single variable, providing efficient ways to organize, access and manipulate collections of data using indexes.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Arrays in Java are used to store multiple values of the same data type in a single variable. They provide an efficient way to organize, access and manipulate collections of data using indexes.

What are Arrays in Java?

An array is a collection of similar data elements stored under a single variable name. Instead of creating separate variables for each value, arrays allow you to store and manage multiple values together.

Definition List

  • Array: A collection of elements of the same data type stored under a single variable name.
  • Index: The position of an element in an array. Array indexing always starts from 0.
  • One-Dimensional Array: An array that stores elements in a single row.
  • Multidimensional Array: An array containing multiple rows and columns.
  • Jagged Array: An array of arrays where each row can have a different number of elements.

Features of Arrays in Java

  • Stores multiple values in a single variable
  • Contains homogeneous (same type) data
  • Elements are accessed using indexes
  • Index starts from 0
  • Improves code organization and efficiency

Steps to Create an Array

  1. Declare and create memory locations
  2. Assign values
  3. Access and print values

Syntax to Declare an Array in Java

dataType arr[] = new datatype[size];
datatype arr[size];
datatype arr[];

Example of Java Array

class Testarray {
    public static void main(String args[]) {
        int a[] = new int[5];
        a[0] = 10;
        a[1] = 20;
        a[2] = 70;
        a[3] = 40;
        a[4] = 50;

        for (int i = 0; i < a.length; i++)
            System.out.println(a[i]);
    }
}

One-Dimensional Arrays in Java

A one-dimensional array stores values in a single sequence.

Example 01: Array Traversal Using for Loop

package Array_Programs;

public class Array_sample {
    public static void main(String[] args) {
        int[] age = {12, 4, 5};

        System.out.println("Using for Loop:");
        for (int i = 0; i < age.length; i++) {
            System.out.println(age[i]);
        }
    }
}

Example 02: Accessing and Printing Arrays

package Array_Programs;

import java.util.Scanner;

public class Array {
    public static void main(String[] args) {
        int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

        System.out.println(a[2]);

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }

        System.out.println("----Printing through Enhanced for loop----");
        for (int element : a) {
            System.out.println(element);
        }

        int b[];
        b = new int[10];
        int[] c = new int[10];

        for (int element : b) {
            System.out.println(element);
        }

        for (int i = 0; i < 3; i++) {
            Scanner in = new Scanner(System.in);
            System.out.println("Enter The Number");
            c[i] = in.nextInt();
        }
        for (int element : c) {
            System.out.println(element);
        }
    }
}

Enhanced for Loop in Java Arrays

The enhanced for loop simplifies array traversal. It is easier to read, requires no index management and reduces coding errors.

for (datatype variable : array) {
    // code
}

Two-Dimensional Arrays in Java

A two-dimensional array stores data in rows and columns, similar to a matrix.

datatype variable_name[][];
// or
datatype[][] variable_name;

Example 03: Two-Dimensional Array

package Array_Programs;

public class Two_Array {
    public static void main(String args[]) {
        int a[][] = {
            {10, 20, 30},
            {40, 50, 60},
            {70, 80, 90}
        };

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(" " + a[i][j]);
            }
            System.out.println("");
        }

        int[][] b = new int[10][10];
        int[][][] c = new int[10][10][10];
        b[0][0] = 10;
    }
}

Jagged Arrays in Java

A jagged array contains rows with different numbers of columns.

Example 09: Jagged Array

package Array_Programs;

public class Jagged_array {
    public static void main(String[] args) {
        int a[][] = {
            {10, 20, 30, 40},
            {10, 20, 30},
            {10, 20, 30, 50}
        };

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.print(" " + a[i][j]);
            }
            System.out.println("");
        }
    }
}

Common Array Operations in Java

Example 04: Calculate Sum and Average

package Array_Programs;

public class Sum_Avg_Array {
    public static void main(String[] args) {
        int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};

        int sum = 0;
        for (int i = 0; i < numbers.length; i++)
            sum = sum + numbers[i];
        System.out.println("Sum of Array is : " + sum);

        double average = sum / numbers.length;
        System.out.println("Average value of the array elements is : " + average);
    }
}

Example 05: Sum Values in an Array

package Array_Programs;

public class Sum_an_Array {
    public static void main(String[] args) {
        int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int sum = 0;

        for (int i : my_array)
            sum += i;
        System.out.println("The sum is " + sum);
        System.out.println("The Average is " + sum / my_array.length);
    }
}

Example 06: Sorting Arrays

package Array_Programs;

import java.util.Arrays;

public class Sorting_Array {
    public static void main(String[] args) {
        int[] Numeric_array = {10, 20, 65, 44, 9, 056, 89, 121, 181, 564, 789};
        String[] String_array = {"JAVA", "PYTHON", "C++", "C programming"};

        System.out.println("Original numeric array : " + Arrays.toString(Numeric_array));
        Arrays.sort(Numeric_array);
        System.out.println("Sorted numeric array : " + Arrays.toString(Numeric_array));

        System.out.println("Original string array : " + Arrays.toString(String_array));
        Arrays.sort(String_array);
        System.out.println("Sorted string array : " + Arrays.toString(String_array));
    }
}

Example 07: Search for an Element

package Array_Programs;

public class Search_Array {
    public static boolean contains(int[] arr, int item) {
        for (int n : arr) {
            if (item == n) {
                return true;
            }
        }
        return false;
    }
}

Example 13: Find Duplicate Elements

package Array_Programs;

public class Duplicate_array {
    public static void main(String[] args) {
        int[] a = {1, 2, 5, 5, 6, 6, 7, 2};
    }
}

Array of Objects in Java

Arrays can also store objects. Each element is an object reference instead of a primitive value.

Example 14: Array of Objects

package Array_Programs;

class Student {
    public int roll_no;
    public String name;

    Student(int roll_no, String name) {
        this.roll_no = roll_no;
        this.name = name;
    }
}

FAQ

1. What is an array in Java?

An array is a collection of elements of the same data type stored under a single variable name.

2. What is the starting index of an array in Java?

Array indexing always starts at 0.

3. What is the difference between a 2D array and a jagged array?

A 2D array usually has equal columns in every row, while a jagged array can have different numbers of columns in each row.

Arrays store multiple values of the same type in one variable.
Array index always starts from 0.
Use array.length to get the total number of elements.
Enhanced for loop simplifies array traversal without indexes.
2D arrays store data in rows and columns like a matrix.
Jagged arrays allow rows with different column counts.
Arrays.sort() sorts both numeric and string arrays.

Where Java is used

Java in real-world development

One-Dimensional Array

Stores elements in a single sequence. Access elements using index starting from 0.

Two-Dimensional Array

Stores data in rows and columns like a matrix. Declared using double brackets [][].

Jagged Array

An array of arrays where each row can have a different number of columns.

Enhanced for Loop

Simplifies array traversal. No index management needed. Reduces coding errors.

Array Sorting

Use Arrays.sort() to sort numeric and string arrays in ascending order.

Array of Objects

Each element stores an object reference. Useful for student records, inventory and employee systems.

Prev: ModifiersBack to hub