Java Arrays
Arrays are one of the most fundamental data structures in Java. They allow
you to store multiple values of the same type in a single variable, making
programs more efficient, organized, and scalable compared to using many
individual variables.
What Is an Array in Java?
An array is a fixed-size container that holds a sequence of elements of the
same data type. Each element is stored at a specific position called an
index.
Instead of declaring multiple variables like:
String city1 = "Chennai";
String city2 = "Mumbai";
String city3 = "Delhi";
You can store them in a single array:
String[] cities = {"Chennai", "Mumbai", "Delhi"};
Declaring and Initializing Arrays
1 Declare an Array
dataType[] arrayName;
Example:
double[] temperatures;
2 Declare and Initialize with Values
double[] temperatures = {32.5, 30.0, 29.8, 31.2};
3 Create an Integer Array
int[] scores = {85, 90, 78, 92};
Accessing Array Elements
Each element in an array is accessed using its index. Array indexing in
Java starts at 0.
public class ArrayAccessExample {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango",
"Orange"};
System.out.println("First fruit: " +
fruits[0]);
System.out.println("Third fruit: " +
fruits[2]);
}
}
Output
First fruit: Apple
Third fruit: Mango
Modifying Array Elements
You can change a value by assigning a new value to its index.
public class ArrayModifyExample {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango",
"Orange"};
fruits[1] = "Pineapple";
System.out.println("Updated fruit: " +
fruits[1]);
}
}
Output
Updated fruit: Pineapple
Finding Array Length
The number of elements in an array is obtained using the length
property.
public class ArrayLengthExample {
public static void main(String[] args) {
int[] marks = {72, 85, 90, 68,
88};
System.out.println("Total marks entries: " +
marks.length);
}
}
Output
Total marks entries: 5
Creating Arrays with the new Keyword
You can create an empty array by specifying its size and assign values
later.
public class ArrayNewKeywordExample {
public static void main(String[] args) {
String[] countries = new
String[3];
countries[0] = "India";
countries[1] = "Japan";
countries[2] = "Germany";
System.out.println(countries[0]);
}
}
Different Ways to Initialize Arrays
Both of the following approaches create identical arrays:
// Explicit creation
String[] colors = new String[] {"Red", "Green", "Blue"};
// Shorthand initialization (preferred)
String[] colors = {"Red", "Green", "Blue"};
Java Arrays Loop
Iterating over arrays is a fundamental programming task in Java. You
can traverse array elements using either a traditional for loop or the
enhanced for-each loop, depending on whether you need index access or
simple value traversal.
This guide explains both approaches with clear examples and
best-practice recommendations.
Loop Through an Array Using a for Loop
A standard for loop is ideal when you need control over the index
position of each element. The loop typically runs from 0 to
array.length - 1.
Example 1: Printing All Array Elements
public class ArrayForLoopExample {
public static void main(String[] args) {
String[] courses = {"Java", "Python", "Data
Science", "Web Dev"};
for (int i = 0; i < courses.length; i++)
{
System.out.println("Course "
+ i + ": " + courses[i]);
}
}
}
Output
Course 0: Java
Course 1: Python
Course 2: Data Science
Course 3: Web Dev
Example 2: Iterating Through Numeric Arrays
public class ArrayNumbersLoop {
public static void main(String[] args) {
int[] ages = {18, 21, 25, 30,
35};
for (int i = 0; i < ages.length; i++)
{
System.out.println("Age
value: " + ages[i]);
}
}
}
Calculating the Sum of Array Elements
Combining loops with arrays enables useful operations such as
aggregation, searching, and filtering.
Example 3: Sum and Average of Array Values
public class ArraySumExample {
public static void main(String[] args) {
int[] sales = {120, 200, 150, 175,
90};
int total = 0;
for (int i = 0; i < sales.length; i++)
{
total +=
sales[i];
}
double average = (double) total /
sales.length;
System.out.println("Total sales: " +
total);
System.out.println("Average sales: " +
average);
}
}
Loop Through an Array Using for-each
The enhanced for loop (for-each) is designed specifically for iterating
over arrays and collections. It automatically visits each element
without requiring an index.
For-Each Syntax
for (dataType element : arrayName) {
// use element
}
The colon : is read as “in”, meaning:
for each element in array
Example 4: Reading Array Elements with For-Each
public class ArrayForEachExample {
public static void main(String[] args) {
String[] cities = {"Chennai", "Bangalore",
"Hyderabad", "Pune"};
for (String city : cities) {
System.out.println("City: " +
city);
}
}
}
When You Need Index + Value
If your logic depends on element position (index), use a traditional
for loop.
Example 5: Displaying Positions and Values
public class ArrayIndexExample {
public static void main(String[] args) {
String[] players = {"Asha", "Ravi",
"Meera", "Karan"};
for (int i = 0; i < players.length; i++)
{
System.out.println("Position
" + i + " → " + players[i]);
}
}
}
Java Multidimensional Arrays
A multidimensional array in Java is an array whose elements are
themselves arrays. The most commonly used type is the two-dimensional
(2D) array, which represents data in a rows × columns structure similar
to a table or matrix.
Multidimensional arrays are widely used in matrices, grids, game
boards, tabular data, and scientific computing.
What Is a 2D Array in Java?
A 2D array stores values in rows and columns.
int[][] matrix = {
{2, 5, 7},
{4, 1, 9}
};
Structure
- Row 0 → {2, 5, 7}
- Row 1 → {4, 1, 9}
Accessing Elements in a 2D Array
To access a value, specify both row index and column index:
array[row][column]
Remember: indexing starts at 0.
Example 1: Accessing Specific Cells
public class MatrixAccessExample {
public static void main(String[] args) {
int[][] matrix = {
{2, 5, 7},
{4, 1, 9}
};
System.out.println("Row 1, Col 2: " +
matrix[1][2]);
System.out.println("Row 0, Col 1: " +
matrix[0][1]);
}
}
Output
Row 1, Col 2: 9
Row 0, Col 1: 5
Modifying Elements in a 2D Array
You can update values using the same index notation.
Example 2: Updating Matrix Values
public class MatrixModifyExample {
public static void main(String[] args) {
int[][] matrix = {
{10, 20, 30},
{40, 50, 60}
};
matrix[1][1] = 99;
System.out.println("Updated value: " +
matrix[1][1]);
}
}
Determining Rows and Columns
- Total rows → array.length
- Columns in a row → array[row].length
This allows jagged arrays (rows with different column
counts).
Example 3: Finding Dimensions
public class MatrixSizeExample {
public static void main(String[] args) {
int[][] data = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};
System.out.println("Rows: " +
data.length);
for (int r = 0; r < data.length;
r++) {
System.out.println("Columns in row " + r + ": " +
data[r].length);
}
}
}
Looping Through a Multidimensional Array
To visit every element, use nested loops.
Example 4: Traversing with Nested for Loops
public class MatrixTraversal {
public static void main(String[] args) {
int[][] grid = {
{3, 6, 9},
{2, 4, 8}
};
for (int row = 0; row < grid.length;
row++) {
for (int col = 0; col
< grid[row].length; col++) {
System.out.println(
"grid[" + row + "][" + col + "] = " +
grid[row][col]
);
}
}
}
}
Example 5: Traversing with For-Each Loops
Many developers prefer the enhanced for loop for
readability.
public class MatrixForEachTraversal {
public static void main(String[] args) {
int[][] scores = {
{85, 90, 78},
{88, 92, 80}
};
for (int[] row : scores) {
for (int value : row)
{
System.out.println(value);
}
}
}
}
Key Characteristics of Multidimensional Arrays
- Arrays of arrays
- Accessed with multiple indexes
- Rows may have different lengths (jagged arrays)
- Ideal for tabular or matrix data
- Traversed using nested loops
Common Use Cases
- Matrices and mathematical operations
- Game boards (tic-tac-toe, chess)
- Seating layouts
- Image pixel grids
- Data tables