java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Java Arrays Tutorial for Beginners
Last Updated on: 23rd Oct 2025 11:14:58 AM
Welcome to this beginner-friendly tutorial on Arrays in Java! Arrays are a fundamental data structure in Java used to store multiple values of the same type in a single variable. They’re perfect for organizing data like a list of numbers, names, or scores. This tutorial is designed for beginners, with clear explanations and practical examples you can run in any Java environment (e.g., Eclipse, IntelliJ, or online compilers like Repl.it).
By the end, you’ll understand how to create, use, and manipulate arrays confidently. Let’s get started!
What Is an Array?
An array is a container that holds a fixed number of elements of the same data type (e.g., all integers or all strings). Think of it as a row of lockers, where each locker holds one item, and all items are of the same kind.
Key Features:
-
Fixed Size: Once created, an array’s size cannot change.
-
Indexed: Elements are accessed using indices (starting from 0).
-
Same Type: All elements must be of the same data type (e.g., int, String).
Real-World Analogy: An array is like a tray of cupcakes—each slot holds one cupcake, and you can access them by their position (first, second, etc.).
Types of Arrays in Java
Java supports two main types of arrays:
-
Single-Dimensional Arrays: A linear list of elements of the same type.
-
Multidimensional Arrays: Arrays of arrays, typically used for grids or tables (e.g., 2D or 3D arrays).
We’ll explore both types with examples later in the tutorial.
1. Declaring and Creating an Array
To use an array, you must declare it and specify its size. This applies to both single-dimensional and multidimensional arrays.
Syntax for Declaration:
dataType[] arrayName; // Preferred style for single-dimensional
// OR
dataType arrayName[];
// For multidimensional (e.g., 2D)
dataType[][] arrayName;
-
dataType: Type of elements (e.g., int, double, String).
-
arrayName: Name of the array.
Creating an Array:
arrayName = new dataType[size]; // Single-dimensional
// OR
arrayName = new dataType[rows][columns]; // 2D array
-
size: Number of elements (or rows/columns for multidimensional).
-
The new keyword allocates memory.
Combined Declaration and Creation:
dataType[] arrayName = new dataType[size]; // Single-dimensional
dataType[][] arrayName = new dataType[rows][columns]; // 2D
Example: Creating a Single-Dimensional Array
public class SingleArrayDeclaration {
public static void main(String[] args) {
// Declare and create an array of 5 integers
int[] numbers = new int[5];
// Assign values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Print an element
System.out.println("First number: " + numbers[0]); // 10
}
}
Output:
First number: 10
Explanation:
-
int[] numbers = new int[5] creates a single-dimensional array of 5 integers, initialized to 0.
-
numbers[0] accesses the first element (index 0).
-
Indices range from 0 to size-1 (here, 0 to 4).
Beginner Tip: Trying to access an index outside the array’s range (e.g., numbers[5]) causes an ArrayIndexOutOfBoundsException.
2. Initializing an Array
You can initialize an array with values at creation using an array initializer. This works for both single-dimensional and multidimensional arrays.
Syntax:
dataType[] arrayName = {value1, value2, ..., valueN}; // Single-dimensional
dataType[][] arrayName = {{value1, value2}, {value3, value4}}; // 2D
Example: Single-Dimensional Array Initializer
public class SingleArrayInitializer {
public static void main(String[] args) {
// Initialize array with values
String[] fruits = {"Apple", "Banana", "Orange"};
// Print all elements
System.out.println("First fruit: " + fruits[0]); // Apple
System.out.println("Second fruit: " + fruits[1]); // Banana
System.out.println("Third fruit: " + fruits[2]); // Orange
}
}
Output:
First fruit: Apple
Second fruit: Banana
Third fruit: Orange
Explanation:
-
The array fruits is created with 3 elements.
-
No new keyword is needed when using the initializer syntax.
Real-World Analogy: Like filling a tray with specific cupcakes (chocolate, vanilla, strawberry) when you set it up.
3. Accessing and Modifying Array Elements
Arrays use indices to access or change elements. Indices start at 0 for both single-dimensional and multidimensional arrays.
Example: Modifying Single-Dimensional Array
public class ArrayModify {
public static void main(String[] args) {
int[] scores = new int[3];
scores[0] = 85;
scores[1] = 90;
scores[2] = 95;
// Modify an element
scores[1] = 88;
// Print all elements
System.out.println("Score 1: " + scores[0]); // 85
System.out.println("Score 2: " + scores[1]); // 88
System.out.println("Score 3: " + scores[2]); // 95
}
}
Output:
Score 1: 85
Score 2: 88
Score 3: 95
Explanation:
-
scores[1] = 88 changes the second element from 90 to 88.
-
Use the index to read or update specific elements.
4. Looping Through Arrays
Loops are ideal for processing array elements. The for loop and for-each loop work for both single-dimensional and multidimensional arrays.
Example: Using a for Loop (Single-Dimensional)
public class SingleArrayLoop {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Loop through array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
Explanation:
-
numbers.length gives the array’s size (5 here).
-
The loop iterates from index 0 to length-1.
Enhanced for Loop (for-each)
The for-each loop simplifies iterating over arrays.
Syntax:
for (dataType variable : arrayName) {
// Use variable
}
Example: for-each Loop (Single-Dimensional)
public class ForEachExample {
public static void main(String[] args) {
String[] colors = {"Red", "Blue", "Green"};
// for-each loop
for (String color : colors) {
System.out.println("Color: " + color);
}
}
}
Output:
Color: Red
Color: Blue
Color: Green
Explanation:
-
The for-each loop assigns each element to color without needing an index.
-
Best for reading elements, not modifying them.
Real-World Analogy: Like checking each item in a shopping list one by one.
5. Arrays with User Input
Let’s use Scanner to create and fill a single-dimensional array with user input.
import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask for array size
System.out.print("Enter the number of elements: ");
int size = scanner.nextInt();
// Create array
int[] numbers = new int[size];
// Input elements
for (int i = 0; i < size; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
// Print array
System.out.println("Your array:");
for (int num : numbers) {
System.out.print(num + " ");
}
scanner.close();
}
}
Sample Run:
Enter the number of elements: 3
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Your array:
10 20 30
Explanation:
-
The user specifies the array size.
-
A for loop collects elements into the array.
-
A for-each loop prints the array.
6. Multidimensional Arrays
A multidimensional array is an array of arrays, commonly used for grids or tables. The most common type is a 2D array (rows and columns), but you can have 3D or higher-dimensional arrays.
Syntax for 2D Array:
dataType[][] arrayName = new dataType[rows][columns];
Example: 2D Array
public class TwoDArray {
public static void main(String[] args) {
// 2x3 array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
// Print 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:
1 2 3
4 5 6
Explanation:
-
matrix.length gives the number of rows (2).
-
matrix[i].length gives the number of columns in row i (3).
-
Nested loops access each element: matrix[i][j] (row i, column j).
Real-World Analogy: Like a spreadsheet with rows and columns.
Example: 3D Array
A 3D array is an array of 2D arrays, like a cube of data.
public class ThreeDArray {
public static void main(String[] args) {
// 2x2x2 3D array
int[][][] cube = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
// Print 3D array
for (int i = 0; i < cube.length; i++) {
for (int j = 0; j < cube[i].length; j++) {
for (int k = 0; k < cube[i][j].length; k++) {
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
Output:
1 2
3 4
5 6
7 8
Explanation:
-
cube is a 3D array with 2 layers, each containing a 2x2 2D array.
-
Three nested loops access each element: cube[i][j][k].
Note: Higher-dimensional arrays (4D, etc.) are rare but follow the same pattern.
7. Common Issues and Solutions
-
Problem: ArrayIndexOutOfBoundsException.
-
Solution: Ensure indices are within 0 to length-1 for each dimension.
-
-
Problem: Array size cannot be changed.
-
Solution: Use ArrayList (advanced topic) for dynamic sizes.
-
-
Problem: Wrong data type in array.
-
Solution: Match the array type to the data (e.g., String[] for strings).
-
-
Problem: Incorrect multidimensional array access.
-
Solution: Use correct indices for each dimension (e.g., matrix[i][j] for 2D).
-
8. Practice Tips
-
Experiment: Create arrays of different types (e.g., double[], char[][]) or calculate the sum of elements.
-
Test Code: Use an online compiler to run examples.
-
Common Mistake: Don’t access indices beyond the array’s size.
-
Quiz Yourself: What’s the index of “Orange” in String[] fruits = {"Apple", "Banana", "Orange"}? (Answer: 2)
-
Challenge: Try printing a 2D array in a pattern (e.g., a multiplication table).
Summary
-
Array Types:
-
Single-Dimensional: Linear list of elements (e.g., int[]).
-
Multidimensional: Arrays of arrays (e.g., 2D for grids, 3D for cubes).
-
-
Declaration/Creation: int[] arr = new int[size] or initializer {1, 2, 3}.
-
Access/Modify: Use indices (arr[0], matrix[i][j]).
-
Loops: Use for or for-each for single-dimensional; nested loops for multidimensional.
-
Next Steps: Combine arrays with methods, loops, or input/output for tasks like sorting or searching.
You’re now ready to work with single-dimensional and multidimensional arrays in Java! Keep practicing, and happy coding! ![]()
.png)