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.
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.
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]);
}
}
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.
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.
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.
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]);
}
}
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.
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.
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);
}
}
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.
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.
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]);
}
}
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.
Since arrays often contain many values, loops are commonly used to process every element without writing repetitive code for each individual index.
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]);
}
}
}
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.
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.
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);
}
}
}
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.
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.
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);
}
}
CS Engineering Gyan total weekly views: 9550 CS Engineering Gyan average daily views: 1910.0
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);
}
}
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.
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.
dataType[][] arrayName = new dataType[rows][columns];
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]);
}
}
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.
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.
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]);
}
}
}
}
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.
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.
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)");
}
}
}
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 | 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. |
| 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. |
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.