CS Engineering Gyan

Arrays in Java

When a program needs to work with a single value, a regular variable is enough. But real-world applications rarely deal with just one piece of information at a time. Whether it is a list of student marks, a set of monthly video upload counts, or a collection of product prices, programs often need to store and manage multiple related values together. This is exactly the problem arrays are designed to solve.

An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. Instead of creating separate variables for every individual value, an array lets you group them together and access each one using a numeric position, known as an index.

In this tutorial, you will learn how to declare and initialize arrays, how to access and modify their elements, how multidimensional arrays work, and how to use loops to process array data efficiently.


What is an Array in Java?

An array is a fixed-size collection of elements that are all of the same data type, stored in contiguous memory locations. Once an array is created, its size cannot be changed, though the values stored inside it can be updated freely.

Example

public class ArrayIntroExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[] weeklyViews = {1200, 1500, 1800, 2100, 2400};

        System.out.println(channel + " views on day 3: " + weeklyViews[2]);

    }

}

Output

CS Engineering Gyan views on day 3: 1800

In this example, weeklyViews is an array holding five integer values. Notice that array indexing in Java starts from zero, so the third day's views are accessed using index 2, not index 3.


Declaring and Creating Arrays

Creating an array in Java generally involves two steps: declaring the array with a specific data type, and then creating the actual array object that will hold the values, often specifying its size.

Syntax

dataType[] arrayName;

arrayName = new dataType[size];

These two steps can also be combined into a single line, which is a common approach for simple programs.

Example

public class ArrayDeclarationExample {

    public static void main(String[] args) {

        int[] subscriberCounts = new int[5];

        subscriberCounts[0] = 40000;

        subscriberCounts[1] = 42000;

        subscriberCounts[2] = 45000;

        System.out.println("First recorded count: " + subscriberCounts[0]);

    }

}

Output

First recorded count: 40000

When an array is created using the new keyword without directly specifying values, Java automatically fills it with default values, such as zero for numeric types, until you assign actual values to each position.


Initializing Arrays with Values

Java also allows you to declare and fill an array with values at the same time, without needing to specify the size manually. The size is automatically determined based on how many values you provide.

Example

public class ArrayInitializationExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        String[] playlists = {"Java Basics", "OOPs Concepts", "DBMS", "Operating Systems", "Placement Prep"};

        System.out.println(channel + " first playlist: " + playlists[0]);

        System.out.println(channel + " total playlists: " + playlists.length);

    }

}

Output

CS Engineering Gyan first playlist: Java Basics

CS Engineering Gyan total playlists: 5

The length property is particularly useful, since it tells you exactly how many elements an array contains, without needing to count them manually or hardcode a fixed number into your program.


Accessing and Modifying Array Elements

Every element inside an array can be accessed or updated using its index, which always starts at zero for the first element and goes up to one less than the array's total length.

Example

public class ArrayModificationExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[] videoLikes = {320, 450, 500};

        System.out.println(channel + " likes on video 2: " + videoLikes[1]);

        videoLikes[1] = 600;

        System.out.println(channel + " updated likes on video 2: " + videoLikes[1]);

    }

}

Output

CS Engineering Gyan likes on video 2: 450

CS Engineering Gyan updated likes on video 2: 600

Attempting to access an index that does not exist, such as a negative number or a value equal to or greater than the array's length, will cause Java to throw an ArrayIndexOutOfBoundsException, which is one of the most common errors beginners encounter while working with arrays.


Traversing an Array Using a for Loop

Since arrays often contain many values, loops are commonly used to process every element without writing repetitive code for each individual index.

Example

public class ArrayTraversalExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[] weeklyUploads = {2, 3, 1, 4, 2};

        for (int i = 0; i < weeklyUploads.length; i++) {

            System.out.println(channel + " uploads in week " + (i + 1) + ": " + weeklyUploads[i]);

        }

    }

}

Output

CS Engineering Gyan uploads in week 1: 2

CS Engineering Gyan uploads in week 2: 3

CS Engineering Gyan uploads in week 3: 1

CS Engineering Gyan uploads in week 4: 4

CS Engineering Gyan uploads in week 5: 2

Using weeklyUploads.length inside the loop condition ensures the loop automatically adjusts if the array size changes, rather than relying on a fixed, hardcoded number.


Traversing an Array Using the Enhanced for Loop

Java also allows arrays to be traversed using the enhanced for loop, which simplifies the syntax further by removing the need to manage an index manually.

Example

public class EnhancedForArrayExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        String[] topics = {"Arrays", "Strings", "Loops", "OOPs"};

        System.out.println(channel + " upcoming topics:");

        for (String topic : topics) {

            System.out.println("- " + topic);

        }

    }

}

Output

CS Engineering Gyan upcoming topics:

- Arrays

- Strings

- Loops

- OOPs

The enhanced for loop is ideal when you only need to read through each element in order, without requiring the index value itself for any calculations.


Common Array Operations

Beyond simple traversal, arrays are often used to perform calculations such as finding a total, an average, or the largest and smallest values within a dataset.

Example: Finding the Sum and Average

public class ArraySumExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[] dailyViews = {1500, 1800, 2100, 1950, 2200};

        int total = 0;

        for (int views : dailyViews) {

            total += views;

        }

        double average = (double) total / dailyViews.length;

        System.out.println(channel + " total weekly views: " + total);

        System.out.println(channel + " average daily views: " + average);

    }

}

Output

CS Engineering Gyan total weekly views: 9550

CS Engineering Gyan average daily views: 1910.0

Example: Finding the Maximum Value

public class ArrayMaxExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[] dailyViews = {1500, 1800, 2100, 1950, 2200};

        int maxViews = dailyViews[0];

        for (int views : dailyViews) {

            if (views > maxViews) {

                maxViews = views;

            }

        }

        System.out.println(channel + " highest daily views: " + maxViews);

    }

}

Output

CS Engineering Gyan highest daily views: 2200

These kinds of operations, summing values, calculating averages, and finding maximums or minimums, form the basis of many real-world programs that analyze collections of data.


Multidimensional Arrays

Java also supports multidimensional arrays, which are essentially arrays of arrays. These are especially useful for representing data that naturally fits into a grid or table format, such as rows and columns.

Syntax

dataType[][] arrayName = new dataType[rows][columns];

Example

public class TwoDArrayExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[][] monthlyViews = {

            {1200, 1400, 1600},

            {1800, 2000, 2200}

        };

        System.out.println(channel + " views for month 2, week 3: " + monthlyViews[1][2]);

    }

}

Output

CS Engineering Gyan views for month 2, week 3: 2200

Here, monthlyViews represents two months, each containing three weekly values. The first index selects the month, while the second index selects the specific week within that month.


Traversing a Multidimensional Array

Processing every element inside a multidimensional array typically requires nested loops, where the outer loop moves through each row and the inner loop moves through each column within that row.

Example

public class TwoDArrayTraversalExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int[][] monthlyViews = {

            {1200, 1400, 1600},

            {1800, 2000, 2200}

        };

        for (int month = 0; month < monthlyViews.length; month++) {

            System.out.println(channel + " month " + (month + 1) + " weekly views:");

            for (int week = 0; week < monthlyViews[month].length; week++) {

                System.out.println("  Week " + (week + 1) + ": " + monthlyViews[month][week]);

            }

        }

    }

}

Output

CS Engineering Gyan month 1 weekly views:

  Week 1: 1200

  Week 2: 1400

  Week 3: 1600

CS Engineering Gyan month 2 weekly views:

  Week 1: 1800

  Week 2: 2000

  Week 3: 2200

This nested structure mirrors how the data itself is organized, making it a natural fit for working with tables, grids, or any information that has two related dimensions.


Array of Objects

Arrays are not limited to primitive data types like integers or characters. They can also store reference types, including objects created from custom classes, allowing you to manage collections of more complex data.

Example

class Video {

    String title;

    int views;

    Video(String title, int views) {

        this.title = title;

        this.views = views;

    }

}

public class ObjectArrayExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        Video[] videos = new Video[2];

        videos[0] = new Video("Java Arrays Explained", 5400);

        videos[1] = new Video("Loops in Java", 4200);

        for (Video video : videos) {

            System.out.println(channel + " - " + video.title + " (" + video.views + " views)");

        }

    }

}

Output

CS Engineering Gyan - Java Arrays Explained (5400 views)

CS Engineering Gyan - Loops in Java (4200 views)

This example demonstrates how arrays and object-oriented programming work together, allowing structured data, such as a video's title and view count, to be grouped and managed efficiently.


Advantages and Limitations of Arrays

Advantages Limitations
Allows efficient storage and access of multiple related values. Size is fixed once the array is created and cannot be resized.
Elements can be accessed quickly using their index. All elements must be of the same data type.
Works well with loops for processing large sets of data. Inserting or removing elements requires manual shifting of values.

Best Practices While Using Arrays


Common Mistakes Beginners Make

Mistake Correct Practice
Accessing an index equal to the array's length. Remember that valid indexes range from 0 to length minus 1.
Assuming array size can be changed after creation. Create a new array with the required size if more space is needed.
Forgetting that array indexing starts at zero. Always treat the first element as index 0, not index 1.
Confusing rows and columns while working with multidimensional arrays. Carefully track which index represents rows and which represents columns.

Frequently Asked Interview Questions

  1. What is an array in Java?
    An array is a fixed-size collection that stores multiple values of the same data type under a single variable name.
  2. What index does array numbering start from in Java?
    Array indexing in Java always starts from zero, not one.
  3. What happens if you access an invalid array index?
    Java throws an ArrayIndexOutOfBoundsException when an invalid index is accessed.
  4. Can the size of an array be changed after it is created?
    No, once an array is created, its size remains fixed for its entire lifetime.
  5. What is the purpose of the length property in arrays?
    It returns the total number of elements the array can hold.
  6. What is the difference between a one-dimensional and a multidimensional array?
    A one-dimensional array stores a single list of values, while a multidimensional array stores data arranged in rows and columns.
  7. Can an array store objects instead of primitive values?
    Yes, arrays can store reference types, including objects created from custom classes.
  8. Why is the enhanced for loop useful for arrays?
    It simplifies traversal by automatically moving through each element without requiring manual index management.

Summary

Arrays provide an efficient way to store and manage multiple related values in Java, whether you are working with simple numeric data or more complex objects. By understanding how to declare, initialize, access, and modify arrays, you gain the ability to organize data in a structured and predictable way.

Combined with loops, arrays become even more powerful, allowing you to process large sets of data with just a few lines of code. Multidimensional arrays further extend this capability, letting you represent grid-like data such as tables and matrices naturally within your programs.

With a solid understanding of arrays, you are now ready to explore methods in Java, which allow you to organize code into reusable blocks that can operate on data, including arrays, in a structured and modular way.


← Previous: Loops in Java Next: Methods in Java →

Home Visit Our YouTube Channel