Navigation
Java Full Course: Mastering the Language Arrays in Java
Arrays in Java
(Complete Notes | Beginner to Advanced | Professional & Exam-Oriented | Masterclass)
1. Introduction to Arrays
An array is a fixed size, indexed collection of elements of the same type. It allows you to store and manage multiple values under a single variable name.
Arrays in Java are classified into two broad categories:
- Single dimensional arrays – a linear sequence of elements (e.g., an array of integers).
- Multi dimensional arrays – arrays whose elements are themselves arrays. These can be:
- Rectangular arrays – each row has the same number of columns.
- Jagged arrays – rows can have different lengths.
All arrays are objects in Java, have a length property, and use zero based indexing. They provide efficient direct access but have a fixed size after creation.
In the following sections, we will cover declaration, creation, initialization, element access, multi dimensional arrays, and common utility methods.
2. Single Dimensional Arrays (One Dimensional Arrays)
A single dimensional array is a container that holds a fixed number of values of a single type. The values are stored in contiguous memory locations, and each element can be accessed directly using an integer index. Arrays are objects in Java, which means they have methods (like clone()) and a public field length.
2.1 Declaring an Array
Declaration does not allocate memory; it simply tells the compiler that a variable will refer to an array of a given type.
- The first form (
int[] numbers) is preferred because it clearly indicates thatnumbersis an array ofint. - You can declare multiple arrays in one line:
The second form can be confusing; the first style avoids this pitfall.
- At declaration, no array is created;
numbersis a reference variable that can later point to an array object.
2.2 Creating an Array (Instantiation)
To create an array, you use the new keyword followed by the type and the size in square brackets. The size can be a literal, a variable, or an expression, but it must be a non negative int.
- The array size is fixed at creation and cannot change later.
- If the size is given by a variable, it is evaluated at runtime:
Memory behavior: The new operator allocates memory on the heap for the array object. All elements are initialized to their default values (see §2.4).
You can combine declaration and creation:
If the size is zero, the array is empty (no elements), but it is a valid object:
2.3 Initializing an Array
Arrays can be initialized in several ways.
a) Using an Array Initializer (Inline)
- The size is inferred from the number of elements.
- This form can only be used at declaration. It is equivalent to:
b) Using new with an Array Initializer
- This syntax can be used anywhere, e.g., to re assign an existing array variable:
c) Assigning Values Individually
After creation, you can assign each element:
- If you don't assign a value, the element retains its default value.
d) Using a Loop
2.4 Default Values
When an array is created with new, all elements are automatically set to the default value for that type. This is guaranteed by the Java language.
| Element Type | Default Value |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 (or 0.0f for float) |
char | '\u0000' (null character) |
boolean | false |
| Object reference | null |
Example:
This default initialization happens only when the array is created with new. If you use an array initializer, you provide explicit values.
2.5 Accessing Elements
You access an element by placing its index inside square brackets after the array variable name. Indices are zero based – the first element is at index 0, the last at array.length - 1.
Bounds checking: Java performs runtime bounds checking. If you attempt to access an index less than 0 or greater than or equal to array.length, an ArrayIndexOutOfBoundsException is thrown.
Performance: Bounds checking adds a small overhead, but it ensures safety and prevents memory corruption.
2.6 The length Property
Every array object has a public, final field called length that holds the number of elements. It is not a method; you do not use parentheses.
lengthisfinal; you cannot assign a new value to it.- It is often used in loops to control iteration.
2.7 Iterating Over an Array
a) Traditional for Loop
- You have access to the index, which can be used for calculations or when you need to modify elements.
b) Enhanced for Loop (for-each)
- The variable
valuereceives a copy of each element. For primitive arrays, modifyingvaluedoes not affect the array. For arrays of objects, you can modify the object's state (since the reference is copied, not the object), but you cannot replace the object itself.
c) Using Arrays.toString()
- This is convenient for debugging; it returns a string representation of the array.
d) Using Streams (Java 8+)
2.8 Copying Arrays
Because arrays are objects, assignment does not copy the array; it copies the reference.
To create a separate copy, use one of the following methods.
a) Manual Loop
b) System.arraycopy()
- Parameters: source array, source start index, destination array, destination start index, number of elements.
- It is a native method and very efficient.
c) Arrays.copyOf()
- Creates a new array, copies the specified number of elements. If the new length is larger, the extra elements are filled with default values.
d) clone()
- For arrays,
clone()returns a shallow copy.
[!IMPORTANT] Shallow copy note: For arrays of reference types, all these methods copy the references, not the objects themselves. So changes to the objects themselves (not the array references) will be visible in both arrays.
2.9 Command Line Arguments (main Method)
The main method receives an array of String objects – the command line arguments passed when the program is executed.
If no arguments are provided, args.length is 0 (not null).
2.10 Common Operations on Arrays
a) Sum and Average
b) Finding Maximum/Minimum
c) Linear Search
d) Reversing an Array
e) Sorting (Using Arrays.sort())
- Sorts the array in ascending order using a dual pivot Quicksort (for primitives) or Timsort (for objects).
- For descending order, you can sort and then reverse, or use
Comparatorwith wrapper types.
2.11 Arrays of Objects
Arrays can store references to objects.
[!WARNING] Creating the array does not create the objects; it only allocates space for references. You must instantiate each object separately.
If you forget to create the objects, accessing an element results in a NullPointerException.
2.12 Common Pitfalls and How to Avoid Them
| Pitfall | Example | Solution |
|---|---|---|
| Off by one error | for (int i = 0; i <= arr.length; i++) | Use < arr.length |
| Using length() instead of length | arr.length() (compiles only if arr is a String) | Arrays use length (field), String uses length() (method) |
| Null array reference | int[] arr = null; arr[0] = 5; → NullPointerException | Always initialize arrays before use |
| Index out of bounds | arr[arr.length] | Last index is length - 1 |
| Confusing declaration | int[] a, b; (both arrays) vs int a[], b; (a is array, b is int) | Use the type[] var style to avoid confusion |
| Modifying array while iterating with enhanced for | for (int x : arr) { x = 5; } does not modify array | Use traditional loop for modifications |
| Using == to compare arrays | if (arr1 == arr2) checks reference equality, not content | Use Arrays.equals(arr1, arr2) |
2.13 Best Practices
- Use Arrays utility methods –
sort(),binarySearch(),fill(),equals(),copyOf()– they are well tested and efficient. - Prefer the enhanced for loop when you only need to read elements.
- Validate indices before accessing, especially when the index comes from user input or external sources.
- Consider using ArrayList if you need a dynamically resizable collection. Arrays are best when the size is fixed and known in advance.
- Use
lengthfield consistently; do not hard code sizes. - Document the meaning of the array – what each index represents (e.g.,
grades[0]is the first quiz score). - Initialize arrays immediately when possible, either with default values or with meaningful data.
2.14 Complete Example
2.15 Key Points to Remember
- Arrays are objects that hold a fixed number of elements of a single type.
- Declaration does not allocate memory; creation with
newdoes. - Array indices start at
0and end atlength - 1. - Accessing an invalid index throws
ArrayIndexOutOfBoundsException. - The
lengthfield gives the number of elements (not a method). - Arrays are automatically initialized with default values when created with
new. - You can copy arrays using loops,
System.arraycopy(),Arrays.copyOf(), orclone(). - Use the enhanced for loop for reading, but it cannot modify the array contents.
- For dynamic sizing, consider
ArrayList. - The
Arraysutility class provides many convenient methods.
3. Multi Dimensional Arrays
A multi dimensional array in Java is an array whose elements are themselves arrays. The most common multi dimensional array is the two dimensional array (like a matrix), but Java supports arrays of any number of dimensions (3D, 4D, etc.). Multi dimensional arrays are not stored as a contiguous block of all elements; instead, they are implemented as arrays of arrays. This gives flexibility, including the ability to create jagged arrays (rows of different lengths).
3.1 Declaring Multi Dimensional Arrays
You declare a multi dimensional array by adding multiple pairs of square brackets.
For three dimensions:
- The brackets can be placed with the type or with the variable name, but the
type[][] varstyle is most readable.
3.2 Creating Multi Dimensional Arrays
Creating a multi dimensional array involves allocating memory for each dimension.
a) Creating a Rectangular 2D Array
- This creates an array of 3 elements, each of which is an
int[]of length 4. - All elements are initialized to the default value for
int(0).
b) Creating a 3D Array
c) Creating Jagged Arrays (Rows with Different Lengths)
You can allocate the second dimension separately:
- This is called a jagged array because the rows can have varying lengths.
- Each row is a separate array object.
3.3 Initializing Multi Dimensional Arrays
a) Using an Array Initializer
- This creates a 3×3 rectangular array.
- You can also create a jagged array with an initializer:
b) Using Nested Loops
c) Individual Element Assignment
3.4 Accessing Elements
Use the appropriate number of indices.
For a 3D array:
[!IMPORTANT]
Bounds Checking: Each index must be within the respective dimension's length; otherwise, ArrayIndexOutOfBoundsException is thrown.
3.5 The length Property
For multi dimensional arrays, length gives the number of elements in the first dimension (rows). Each inner array also has its own length.
For jagged arrays:
3.6 Iterating Over Multi Dimensional Arrays
a) Nested Traditional for Loops
b) Enhanced for Loops (for-each)
- For 3D arrays, you need three nested loops.
c) Using Arrays.deepToString()
deepToString()works for arrays of arrays; it produces a string representation of the entire structure.
3.7 Common Operations
a) Sum of All Elements
b) Matrix Multiplication
c) Transpose of a Matrix
3.8 Ragged (Jagged) Arrays
Java allows each inner array to have a different length. This is useful when the data is not rectangular.
Iterating over jagged array:
3.9 Multi Dimensional Arrays of Objects
You can create arrays of objects in multiple dimensions.
Or with initializer:
3.10 Memory Representation
A 2D array int[3][4] is stored as:
- One array of 3 elements, each element is a reference to an
int[]array. - Three separate
int[]arrays, each of length 4, stored elsewhere on the heap.
This means:
matrix[0]is a reference to an array of 4 ints.matrix[1]is another reference, etc.- Accessing
matrix[1][2]involves two dereferences: first get the row array, then the element.
Jagged arrays follow the same model, but the inner arrays can have different lengths.
3.11 Common Pitfalls
| Pitfall | Example | Solution |
|---|---|---|
| Null row in jagged array | int[][] jag = new int[2][]; jag[0][0] = 5; → NullPointerException | Allocate each row before use |
| Inconsistent column lengths assumption | for (int j = 0; j < 3; j++) assuming all rows have 3 columns | Use matrix[i].length |
| Using matrix.length for columns | matrix.length gives rows, not columns | Use matrix[0].length only if rectangular |
| Misplacing brackets in declaration | int[] arr[], var; – var is an int, not array | Use int[][] arr; style |
| Deep copy vs shallow copy | int[][] copy = matrix.clone(); copies only the row references | Use nested loops or deepCopy method |
| Index out of bounds | Accessing matrix[2][3] in a 2×3 matrix | Validate indices with length |
3.12 Best Practices
- Use meaningful names:
matrix,grid,table,pixelsfor 2D;cube,volumefor 3D. - Use
matrix.lengthfor rows andmatrix[0].lengthfor columns only when you are certain the array is rectangular. - Always check row lengths when iterating jagged arrays.
- Prefer enhanced for loops for reading; use index loops when you need to modify elements.
- Use
Arrays.deepEquals()andArrays.deepToString()for deep comparisons and printing. - If performance matters, consider that accessing elements in a multi dimensional array involves multiple dereferences. For critical code, sometimes a flat array is faster.
- When copying multi dimensional arrays, create a deep copy by manually copying each inner array.
3.13 Example: 2D Array Utility Methods
3.14 Multi Dimensional Arrays of More Than Two Dimensions
You can create arrays with any number of dimensions.
Iteration:
For very high dimensions, consider alternative data structures or flattening into a 1D array for performance and simplicity.
3.15 Key Points to Remember
- A multi dimensional array in Java is an array of arrays. Each dimension is a separate array object.
- Rectangular arrays have all inner arrays of the same length; jagged arrays can have varying lengths.
- Declaration:
int[][] matrix;Creation:new int[rows][cols];ornew int[rows][];followed by allocating rows individually. - The
lengthfield on a 2D array gives the number of rows; each row has its ownlength. - Use nested loops or enhanced for loops to iterate.
Arrays.deepToString()andArrays.deepEquals()work on arrays of any depth.- Be careful with null rows in jagged arrays and always initialize them before use.
- Multi dimensional arrays are stored non contiguously; access involves multiple pointer dereferences.
