Java Tutorial 0/145 lessons ~6 min read Lesson 15

    Arrays

    java arrays fixed size zero-based indexing length multidimensional matrix ArrayIndexOutOfBoundsException for-each loop contiguous memory

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    In the previous lesson, you learned how loops help execute a block of code repeatedly.

    However, what if you need to store the marks of 1,000 students?

    Creating separate variables would be inefficient:

    java
    int mark1 = 85;
    int mark2 = 90;
    int mark3 = 78;
    ...

    Managing hundreds or thousands of variables quickly becomes impossible.

    Java solves this problem using Arrays.

    An array allows you to store multiple values of the same data type in a single variable.

    Arrays are one of the most fundamental data structures in Java and are widely used in:

    • Banking Systems
    • E-commerce Applications
    • Game Development
    • Data Processing
    • Machine Learning
    • Spring Boot Applications
    • Collections Framework (internally)

    In this lesson, you'll learn:

    • What is an Array?
    • Why Arrays are Needed
    • Declaring Arrays
    • Creating Arrays
    • Initializing Arrays
    • Accessing Elements
    • Updating Elements
    • Array Length
    • Iterating Arrays
    • Multidimensional Arrays
    • Arrays vs Variables
    • Real-world Examples
    • Best Practices
    • Common Mistakes
    • Hands-on Exercises
    • Professional Interview Questions

    What is an Array?

    An array is a fixed-size collection of elements of the same data type stored in contiguous memory locations.

    Instead of creating multiple variables:

    java
    int s1 = 80;
    int s2 = 85;
    int s3 = 90;

    We can write:

    java
    int[] marks = {80, 85, 90};

    Now all student marks are stored in a single variable.

    Why Do We Need Arrays?

    Imagine storing monthly sales for a company.

    Without arrays:

    java
    double janSales = 12000;
    double febSales = 15000;
    double marSales = 18000;

    With arrays:

    java
    double[] monthlySales = {
    12000,
    15000,
    18000
    };

    Arrays make programs:

    • Easier to maintain
    • More readable
    • Memory efficient
    • Easy to process using loops

    Declaring an Array

    Syntax:

    java
    dataType[] arrayName;

    Example:

    java
    int[] numbers;
    String[] names;
    double[] salaries;

    At this stage, memory is not allocated.

    Creating an Array

    Memory allocation uses the new keyword.

    java
    int[] numbers = new int[5];

    This creates an array capable of storing 5 integers.

    Memory Layout:

    Index
    0 1 2 3 4
    |0|0|0|0|0|

    Each element is initialized with its default value.

    Default Values

    Data TypeDefault Value
    int0
    double0.0
    booleanfalse
    char'\u0000'
    Objectnull

    Example:

    java
    int[] numbers = new int[3];
    System.out.println(numbers[0]);

    Output:

    0

    Initializing Arrays

    Initialization can happen during declaration.

    java
    String[] cities = {
    "Delhi",
    "Mumbai",
    "Hyderabad",
    "Bangalore"
    };

    Accessing Array Elements

    Arrays use zero-based indexing.

    java
    String[] fruits = {
    "Apple",
    "Banana",
    "Orange"
    };
    System.out.println(fruits[0]);
    System.out.println(fruits[2]);

    Output:

    Apple
    Orange

    Updating Array Elements

    Elements can be modified using their index.

    java
    int[] ages = {20, 25, 30};
    ages[1] = 28;
    System.out.println(ages[1]);

    Output:

    28

    Array Length

    Every array has a built-in property called length.

    java
    int[] marks = {80, 90, 70, 95};
    System.out.println(marks.length);

    Output:

    4

    Note: length is a property, not a method.

    Correct:

    java
    marks.length

    Wrong:

    java
    marks.length()

    Iterating Through Arrays

    Using a for loop:

    java
    int[] numbers = {10,20,30,40};
    for(int i = 0; i < numbers.length; i++){
    System.out.println(numbers[i]);
    }

    Output:

    10
    20
    30
    40

    Using Enhanced for Loop

    java
    String[] names = {
    "John",
    "David",
    "Alex"
    };
    for(String name : names){
    System.out.println(name);
    }

    Output:

    John
    David
    Alex

    Use enhanced for loops when you only need to read elements.

    Multidimensional Arrays

    Arrays can contain other arrays.

    Example:

    java
    int[][] matrix = {
    {1,2,3},
    {4,5,6},
    {7,8,9}
    };

    Accessing elements:

    java
    System.out.println(matrix[1][2]);

    Output:

    6

    Memory Representation

    numbers
    +----+----+----+----+
    |10 |20 |30 |40 |
    +----+----+----+----+
    Index
    0 1 2 3

    Arrays occupy contiguous memory, enabling fast index-based access.

    ArrayIndexOutOfBoundsException

    Accessing an invalid index causes an exception.

    java
    int[] arr = {10,20,30};
    System.out.println(arr[5]);

    Output:

    Exception in thread "main"
    java.lang.ArrayIndexOutOfBoundsException

    Always ensure the index is within 0 to length - 1.

    Arrays vs Individual Variables

    Individual VariablesArrays
    Difficult to manageEasy to manage
    More codeLess code
    Cannot iterate easilyLoop-friendly
    Poor scalabilityHighly scalable

    Real-World Example: Student Marks

    java
    int[] marks = {85,90,78,92,88};
    int total = 0;
    for(int mark : marks){
    total += mark;
    }
    double average = (double) total / marks.length;
    System.out.println("Average = " + average);

    Real-World Example: Online Shopping Cart

    java
    String[] cart = {
    "Laptop",
    "Mouse",
    "Keyboard"
    };
    for(String item : cart){
    System.out.println(item);
    }

    Best Practices

    Use Meaningful Names

    java
    int[] employeeIds;

    Better than:

    java
    int[] x;

    Avoid Magic Numbers

    Instead of:

    java
    for(int i=0;i<5;i++)

    Use:

    java
    for(int i=0;i<array.length;i++)

    Prefer Enhanced for Loop for Reading

    Cleaner and less error-prone.

    Validate Indexes

    Always ensure indexes remain within bounds.

    Keep Arrays Immutable if Possible

    Avoid modifying shared arrays unnecessarily.

    Common Mistakes

    Starting Index from 1

    Arrays start at 0, not 1.

    Accessing Invalid Index

    Results in ArrayIndexOutOfBoundsException.

    Forgetting Array Length

    Hardcoding loop limits makes code fragile.

    Confusing length with length()

    Arrays use length; strings use length().

    Mixing Data Types

    An array stores only one data type.

    Hands-on Exercise

    Create a Java program that:

    1. Stores 10 student marks in an array.
    2. Prints all marks using both for and enhanced for loops.
    3. Finds the highest mark.
    4. Finds the lowest mark.
    5. Calculates the average mark.
    6. Creates a 3×3 matrix and prints its elements.
    7. Demonstrates ArrayIndexOutOfBoundsException and then fixes it.

    Summary

    Arrays provide an efficient way to store and manage multiple values of the same type. They simplify repetitive data handling, integrate seamlessly with loops, and form the basis for advanced data structures such as ArrayList, collections, and matrices.

    Key Takeaways

    • Arrays store multiple elements of the same type.
    • Arrays use zero-based indexing.
    • Array size is fixed after creation.
    • Use length to determine array size.
    • Enhanced for loops simplify traversal.
    • Multidimensional arrays represent tables and matrices.
    • Invalid indexes throw ArrayIndexOutOfBoundsException.
    • Arrays are the foundation of many advanced Java data structures.

    Professional Interview Questions

    1What is an array in Java?

    Professional Answer

    An array is a fixed-size data structure that stores multiple elements of the same data type in contiguous memory locations. It provides fast index-based access and is commonly used when the number of elements is known in advance.

    Follow-up Questions

    • Why are arrays faster than linked lists for random access?
    • Can an array store objects?

    Interview Tip: Mention that arrays provide O(1) random access using indexes.

    2What is the difference between length and length()?

    Professional Answer

    length is a property of arrays that returns the number of elements, while length() is a method of the String class that returns the number of characters in a string.

    Follow-up Questions

    • Does ArrayList use length or size()?
    • Why is length not a method for arrays?

    Interview Tip: Remember: Arrays → length, String → length(), Collections → size().

    3What is ArrayIndexOutOfBoundsException?

    Professional Answer

    It is a runtime exception thrown when a program attempts to access an array index that is less than 0 or greater than or equal to the array's length. Proper index validation and loop conditions prevent this exception.

    Follow-up Questions

    • How do you avoid this exception?
    • Can it be caught using a try-catch block?

    Interview Tip: Always iterate from 0 to array.length - 1 to avoid index-related errors.

    Ready to mark this lesson complete?Track your journey across the entire course.