Arrays in Java
Learn how to store and manage multiple values in Java using arrays. Understand array declaration, creation, initialization, indexing, traversal, multidimensional arrays, array methods, searching, sorting, copying, and real-world applications.
Introduction
In the previous lesson, you learned how methods divide programs into smaller and reusable blocks of code. However, programs often need to work with many related values. Creating a separate variable for every value quickly becomes difficult to manage.
int mark1 = 85;
int mark2 = 90;
int mark3 = 78;
int mark4 = 92;
int mark5 = 88;This approach may work for a few values, but it becomes impractical when a program needs to store hundreds or thousands of related values. Arrays solve this problem by storing multiple values of the same type under a single variable name.
int[] marks = {
85, 90, 78, 92, 88
};- What arrays are.
- Why arrays are needed.
- How arrays work in memory.
- The main characteristics of arrays.
- How to declare arrays.
- How to create arrays.
- How to initialize arrays.
- How array literals work.
- Default values of array elements.
- How array indexing works.
- How to access array elements.
- How to modify array elements.
- How to find array length.
- What ArrayIndexOutOfBoundsException means.
- How to traverse arrays.
- How to use for loops with arrays.
- How to use enhanced for loops.
- How to use while and do-while loops.
- How to traverse arrays in reverse.
- How to accept array input.
- How to display arrays.
- How Arrays.toString works.
- How to calculate sum and average.
- How to find maximum and minimum values.
- How to count elements based on conditions.
- How to search arrays.
- How linear search works.
- How binary search works.
- How to sort arrays.
- How bubble sort works.
- How Arrays.sort works.
- How to reverse arrays.
- How array copying works.
- The difference between reference copying and element copying.
- How clone works.
- How Arrays.copyOf works.
- How Arrays.copyOfRange works.
- How System.arraycopy works.
- How to compare arrays.
- How Arrays.equals works.
- How to fill arrays.
- Why arrays are objects.
- How array references work.
- How null arrays behave.
- What anonymous arrays are.
- How to pass arrays to methods.
- How methods modify arrays.
- How to return arrays from methods.
- How one-dimensional arrays work.
- How two-dimensional arrays work.
- How multidimensional arrays work.
- How jagged arrays work.
- How arrays of strings work.
- How arrays of objects work.
- How to solve common array problems.
- Common array errors.
- Best practices for using arrays.
What is an Array?
An array is a fixed-size data structure that stores multiple values of the same type under a single variable name. Each value is stored at a numbered position called an index.
ARRAY: marks
INDEX 0 1 2 3 4
┌─────┬─────┬─────┬─────┬─────┐
VALUE │ 85 │ 90 │ 78 │ 92 │ 88 │
└─────┴─────┴─────┴─────┴─────┘
marks[0]
marks[1]
marks[2]
marks[3]
marks[4]- An array stores multiple values.
- All elements have the same declared type.
- Every element has an index.
- The first index is 0.
- The last index is length - 1.
- The size is fixed after creation.
Why Arrays are Needed
Multiple Values
Store many related values using one variable name.
Indexed Access
Access individual values directly using their index.
Easy Processing
Process all elements efficiently using loops.
Organized Data
Keep related values together in a structured form.
Fast Access
Access any valid element directly using its index.
Foundation
Arrays form the basis of many algorithms and data structures.
Real-World Analogy
Think of an array as a row of numbered lockers. Every locker stores one value, and each locker can be accessed using its number.
LOCKER NUMBER
0 1 2 3
┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐
│ Book │ │ Phone │ │ Keys │ │ Wallet│
└───────┘ └───────┘ └───────┘ └───────┘
│
▼
ARRAY INDEXThe array name identifies the entire collection, while the index identifies a specific position inside the collection.
How Arrays Work
int[] numbers =
new int[5];int[] numbers = new int[5];
│
▼
CREATE ARRAY OBJECT
│
▼
ALLOCATE 5 int ELEMENTS
│
▼
ASSIGN DEFAULT VALUES
│
▼
INDEX 0 1 2 3 4
┌────┬────┬────┬────┬────┐
VALUE │ 0 │ 0 │ 0 │ 0 │ 0 │
└────┴────┴────┴────┴────┘
│
▼
STORE ARRAY REFERENCE
IN numbersArray Characteristics
- Arrays store multiple values.
- All elements use the same declared type.
- Arrays use zero-based indexing.
- Array size is fixed after creation.
- Arrays can store primitive values.
- Arrays can store object references.
- Arrays are objects in Java.
- Arrays are created dynamically at runtime.
- Array elements receive default values.
- Arrays have a length field.
- Arrays can be passed to methods.
- Arrays can be returned from methods.
- Arrays can have multiple dimensions.
Array Declaration
Array declaration creates a variable capable of storing a reference to an array.
int[] numbers;
double[] prices;
String[] names;
boolean[] statuses;int numbers[];
double prices[];
String names[];- Use int[] numbers instead of int numbers[].
- Placing brackets with the type clearly shows that the variable represents an array.
- Both forms compile, but the first form is generally preferred.
Array Creation
numbers = new int[5];new
CREATE NEW OBJECT
int
ELEMENT TYPE
[5]
NUMBER OF ELEMENTSDeclaration and Creation
int[] numbers =
new int[5];int[]
ARRAY TYPE
numbers
REFERENCE VARIABLE
new int[5]
ARRAY OBJECTArray Initialization
int[] numbers =
new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;Array Literal
An array literal creates and initializes an array in a single statement.
int[] numbers = {
10, 20, 30, 40, 50
};String[] languages = {
"Java",
"Python",
"JavaScript",
"C++"
};Default Values
When an array is created using new, Java automatically initializes every element with the default value of its type.
TYPE DEFAULT VALUE
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0
char '\u0000'
boolean false
Object Reference nullint[] numbers =
new int[3];
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);0
0
0Array Indexing
Java arrays use zero-based indexing. This means the first element is stored at index 0 rather than index 1.
ARRAY LENGTH = 5
INDEX 0 1 2 3 4
┌────┬────┬────┬────┬────┐
VALUE │ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴────┴────┴────┴────┘
FIRST INDEX = 0
LAST INDEX = length - 1
= 5 - 1
= 4Accessing Elements
int[] numbers = {
10, 20, 30, 40, 50
};
System.out.println(numbers[0]);
System.out.println(numbers[2]);
System.out.println(numbers[4]);10
30
50Modifying Elements
int[] numbers = {
10, 20, 30
};
numbers[1] = 200;
System.out.println(
numbers[1]
);200Array Length
Every array has a length field that stores the number of elements in the array.
int[] numbers = {
10, 20, 30, 40, 50
};
System.out.println(
numbers.length
);5- Use array.length.
- Do not use array.length().
- String uses the length() method.
- Arrays use the length field.
ArrayIndexOutOfBoundsException
Accessing an index outside the valid range causes ArrayIndexOutOfBoundsException.
int[] numbers = {
10, 20, 30
};
// Valid indexes: 0, 1, 2
System.out.println(
numbers[3]
);- The first valid index is 0.
- The last valid index is array.length - 1.
- Negative indexes are invalid.
- An index equal to array.length is invalid.
Traversing Arrays
Traversing means visiting each element of an array one by one.
START
│
▼
INDEX 0
│
▼
INDEX 1
│
▼
INDEX 2
│
▼
...
│
▼
LAST INDEX
│
▼
ENDUsing for Loop
int[] numbers = {
10, 20, 30, 40, 50
};
for (
int index = 0;
index < numbers.length;
index++
) {
System.out.println(
numbers[index]
);
}Using Enhanced for Loop
int[] numbers = {
10, 20, 30, 40, 50
};
for (int number : numbers) {
System.out.println(number);
}for (int number : numbers)
│ │
│ └── ARRAY
│
└── CURRENT ELEMENTUsing while Loop
int[] numbers = {
10, 20, 30
};
int index = 0;
while (index < numbers.length) {
System.out.println(
numbers[index]
);
index++;
}Using do-while Loop
int[] numbers = {
10, 20, 30
};
int index = 0;
do {
System.out.println(
numbers[index]
);
index++;
} while (index < numbers.length);- A do-while loop executes at least once.
- Accessing index 0 of an empty array causes an exception.
- Check that the array contains elements before using this pattern.
Reverse Traversal
int[] numbers = {
10, 20, 30, 40, 50
};
for (
int index = numbers.length - 1;
index >= 0;
index--
) {
System.out.println(
numbers[index]
);
}for Loop vs Enhanced for Loop
TRADITIONAL for LOOP
Has access to index
Can modify elements by index
Can traverse backward
Can skip positions
More control
ENHANCED for LOOP
Simpler syntax
Directly provides element values
No direct index access
Best for reading every elementArray Input
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =
new Scanner(System.in);
System.out.print(
"Enter array size: "
);
int size =
scanner.nextInt();
int[] numbers =
new int[size];
for (
int index = 0;
index < numbers.length;
index++
) {
System.out.print(
"Enter element "
+ index
+ ": "
);
numbers[index] =
scanner.nextInt();
}
}
}Array Output
for (int number : numbers) {
System.out.println(number);
}for (int number : numbers) {
System.out.print(
number + " "
);
}Arrays.toString()
The Arrays.toString method creates a readable string representation of a one-dimensional array.
import java.util.Arrays;
int[] numbers = {
10, 20, 30, 40
};
System.out.println(
Arrays.toString(numbers)
);[10, 20, 30, 40]Sum of Elements
int[] numbers = {
10, 20, 30, 40
};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println(
"Sum: " + sum
);Average of Elements
int[] numbers = {
10, 20, 30, 40
};
int sum = 0;
for (int number : numbers) {
sum += number;
}
double average =
(double) sum
/ numbers.length;
System.out.println(
"Average: " + average
);Maximum Element
int[] numbers = {
45, 12, 89, 34, 67
};
int maximum =
numbers[0];
for (
int index = 1;
index < numbers.length;
index++
) {
if (numbers[index] > maximum) {
maximum =
numbers[index];
}
}
System.out.println(
"Maximum: " + maximum
);Minimum Element
int[] numbers = {
45, 12, 89, 34, 67
};
int minimum =
numbers[0];
for (
int index = 1;
index < numbers.length;
index++
) {
if (numbers[index] < minimum) {
minimum =
numbers[index];
}
}
System.out.println(
"Minimum: " + minimum
);Count Even and Odd Numbers
int[] numbers = {
10, 15, 20, 25, 30
};
int evenCount = 0;
int oddCount = 0;
for (int number : numbers) {
if (number % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println(
"Even: " + evenCount
);
System.out.println(
"Odd: " + oddCount
);Positive, Negative and Zero
int[] numbers = {
10, -5, 0, 20, -8, 0
};
int positive = 0;
int negative = 0;
int zero = 0;
for (int number : numbers) {
if (number > 0) {
positive++;
} else if (number < 0) {
negative++;
} else {
zero++;
}
}Searching Arrays
Searching means finding whether a particular value exists in an array and, when required, determining its position.
ARRAY SEARCHING
├── Linear Search
│
└── Binary SearchLinear Search
Linear search checks elements one by one from the beginning until the target value is found or the array ends.
int[] numbers = {
10, 20, 30, 40, 50
};
int target = 30;
int foundIndex = -1;
for (
int index = 0;
index < numbers.length;
index++
) {
if (numbers[index] == target) {
foundIndex = index;
break;
}
}
if (foundIndex != -1) {
System.out.println(
"Found at index: "
+ foundIndex
);
} else {
System.out.println(
"Not found"
);
}Linear Search Method
static int linearSearch(
int[] numbers,
int target
) {
for (
int index = 0;
index < numbers.length;
index++
) {
if (numbers[index] == target) {
return index;
}
}
return -1;
}Binary Search
Binary search repeatedly divides a sorted search range into halves. It is much faster than linear search for large sorted arrays.
- Binary search requires sorted data.
- Searching an unsorted array with binary search does not produce reliable results.
- Sort the array before performing binary search.
static int binarySearch(
int[] numbers,
int target
) {
int left = 0;
int right =
numbers.length - 1;
while (left <= right) {
int middle =
left
+ (right - left) / 2;
if (numbers[middle] == target) {
return middle;
}
if (numbers[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}Arrays.binarySearch()
import java.util.Arrays;
int[] numbers = {
10, 20, 30, 40, 50
};
int index =
Arrays.binarySearch(
numbers,
30
);
System.out.println(index);Sorting Arrays
Sorting arranges array elements in a particular order, commonly ascending or descending.
UNSORTED
40 10 30 20
ASCENDING
10 20 30 40
DESCENDING
40 30 20 10Bubble Sort
int[] numbers = {
50, 20, 40, 10, 30
};
for (
int pass = 0;
pass < numbers.length - 1;
pass++
) {
for (
int index = 0;
index < numbers.length - 1 - pass;
index++
) {
if (
numbers[index]
> numbers[index + 1]
) {
int temporary =
numbers[index];
numbers[index] =
numbers[index + 1];
numbers[index + 1] =
temporary;
}
}
}Arrays.sort()
import java.util.Arrays;
int[] numbers = {
50, 20, 40, 10, 30
};
Arrays.sort(numbers);
System.out.println(
Arrays.toString(numbers)
);[10, 20, 30, 40, 50]Partial Sorting
int[] numbers = {
50, 40, 30, 20, 10
};
Arrays.sort(
numbers,
1,
4
);
System.out.println(
Arrays.toString(numbers)
);- The starting index is included.
- The ending index is excluded.
- The range must be valid.
Reversing an Array
int[] numbers = {
10, 20, 30, 40, 50
};
int left = 0;
int right =
numbers.length - 1;
while (left < right) {
int temporary =
numbers[left];
numbers[left] =
numbers[right];
numbers[right] =
temporary;
left++;
right--;
}Copying Arrays
Arrays can be copied in several ways. It is important to distinguish copying an array reference from creating a new array containing copied elements.
Reference Copy
int[] first = {
10, 20, 30
};
int[] second = first;
second[0] = 999;
System.out.println(
first[0]
);999first ───────┐
│
▼
┌──────────────┐
│ 10 │ 20 │ 30 │
└──────────────┘
▲
│
second ───────┘
BOTH VARIABLES REFER
TO THE SAME ARRAYManual Copy
int[] source = {
10, 20, 30
};
int[] copy =
new int[source.length];
for (
int index = 0;
index < source.length;
index++
) {
copy[index] =
source[index];
}clone()
int[] original = {
10, 20, 30
};
int[] copy =
original.clone();
copy[0] = 999;
System.out.println(
original[0]
);10Arrays.copyOf()
int[] original = {
10, 20, 30
};
int[] copy =
Arrays.copyOf(
original,
original.length
);int[] larger =
Arrays.copyOf(
original,
5
);
System.out.println(
Arrays.toString(larger)
);[10, 20, 30, 0, 0]Arrays.copyOfRange()
int[] numbers = {
10, 20, 30, 40, 50
};
int[] copy =
Arrays.copyOfRange(
numbers,
1,
4
);
System.out.println(
Arrays.toString(copy)
);[20, 30, 40]System.arraycopy()
int[] source = {
10, 20, 30, 40, 50
};
int[] destination =
new int[3];
System.arraycopy(
source,
1,
destination,
0,
3
);
System.out.println(
Arrays.toString(destination)
);[20, 30, 40]Comparing Arrays
int[] first = {
10, 20, 30
};
int[] second = {
10, 20, 30
};
System.out.println(
first == second
);falseThe == operator compares array references, not element contents.
Arrays.equals()
int[] first = {
10, 20, 30
};
int[] second = {
10, 20, 30
};
System.out.println(
Arrays.equals(
first,
second
)
);trueFilling Arrays
Sometimes every element of an array needs the same initial value.
Arrays.fill()
int[] numbers =
new int[5];
Arrays.fill(
numbers,
100
);
System.out.println(
Arrays.toString(numbers)
);[100, 100, 100, 100, 100]Arrays as Objects
Arrays are objects in Java. An array variable stores a reference to an array object rather than storing all array elements directly inside the variable.
STACK HEAP
numbers
│
│
└──────────────────────► ┌───────────────┐
│ 10 │ 20 │ 30 │
└───────────────┘
ARRAY OBJECTArray References
int[] first =
new int[3];
int[] second = first;
first[0] = 100;
System.out.println(
second[0]
);100null Arrays
int[] numbers = null;int[] numbers = null;
// NullPointerException
System.out.println(
numbers.length
);Anonymous Arrays
An anonymous array is created without assigning it to a named variable.
printNumbers(
new int[] {
10, 20, 30
}
);Arrays as Method Arguments
static void printNumbers(
int[] numbers
) {
for (int number : numbers) {
System.out.println(number);
}
}
int[] values = {
10, 20, 30
};
printNumbers(values);Modifying Arrays in Methods
static void changeFirst(
int[] numbers
) {
numbers[0] = 999;
}
int[] values = {
10, 20, 30
};
changeFirst(values);
System.out.println(
values[0]
);999Returning Arrays
static int[] createNumbers() {
return new int[] {
10, 20, 30, 40, 50
};
}
int[] numbers =
createNumbers();Variable-Length Arrays
The size of an array can be determined at runtime, but after the array object is created, its length cannot change.
Scanner scanner =
new Scanner(System.in);
System.out.print(
"Enter size: "
);
int size =
scanner.nextInt();
int[] numbers =
new int[size];One-Dimensional Arrays
A one-dimensional array stores elements in a single sequence and uses one index to access each element.
int[] numbers = {
10, 20, 30, 40
};Two-Dimensional Arrays
A two-dimensional array stores arrays inside another array. It is commonly used to represent tables, grids, and matrices.
COLUMN
0 1 2
ROW 0 10 20 30
ROW 1 40 50 60
ROW 2 70 80 902D Array Declaration
int[][] matrix;matrix =
new int[3][4];2D Array Initialization
int[][] matrix = {
{ 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 }
};Accessing 2D Elements
System.out.println(
matrix[1][2]
);matrix[1][2]
│ │
│ └── COLUMN INDEX
│
└───── ROW INDEX
VALUE = 60Traversing 2D Arrays
for (
int row = 0;
row < matrix.length;
row++
) {
for (
int column = 0;
column < matrix[row].length;
column++
) {
System.out.print(
matrix[row][column]
+ " "
);
}
System.out.println();
}2D Array Input
int[][] matrix =
new int[3][3];
for (
int row = 0;
row < matrix.length;
row++
) {
for (
int column = 0;
column < matrix[row].length;
column++
) {
System.out.print(
"Enter value: "
);
matrix[row][column] =
scanner.nextInt();
}
}Rows and Columns
int rows =
matrix.length;int columns =
matrix[0].length;- matrix.length gives the number of rows.
- matrix[row].length gives the number of columns in a specific row.
- Different rows can have different lengths.
- Do not assume every 2D array is rectangular.
Arrays.deepToString()
int[][] matrix = {
{ 10, 20 },
{ 30, 40 }
};
System.out.println(
Arrays.deepToString(matrix)
);[[10, 20], [30, 40]]Jagged Arrays
A jagged array is a multidimensional array whose rows have different lengths.
int[][] numbers = {
{ 10, 20 },
{ 30, 40, 50 },
{ 60 },
{ 70, 80, 90, 100 }
};ROW 0 10 20
ROW 1 30 40 50
ROW 2 60
ROW 3 70 80 90 100Three-Dimensional Arrays
int[][][] data =
new int[2][3][4];int[][][] data = {
{
{ 1, 2 },
{ 3, 4 }
},
{
{ 5, 6 },
{ 7, 8 }
}
};Multidimensional Array Memory
Java multidimensional arrays are arrays of arrays. Each row is a separate array object and can have a different length.
matrix
│
▼
┌───────────┐
│ Reference │────────► [10, 20, 30]
├───────────┤
│ Reference │────────► [40, 50]
├───────────┤
│ Reference │────────► [60, 70, 80, 90]
└───────────┘Matrix Addition
int[][] first = {
{ 1, 2 },
{ 3, 4 }
};
int[][] second = {
{ 5, 6 },
{ 7, 8 }
};
int[][] result =
new int[2][2];
for (
int row = 0;
row < first.length;
row++
) {
for (
int column = 0;
column < first[row].length;
column++
) {
result[row][column] =
first[row][column]
+ second[row][column];
}
}Matrix Transpose
int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int[][] transpose =
new int[3][2];
for (
int row = 0;
row < matrix.length;
row++
) {
for (
int column = 0;
column < matrix[row].length;
column++
) {
transpose[column][row] =
matrix[row][column];
}
}Diagonal Elements
int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (
int index = 0;
index < matrix.length;
index++
) {
System.out.println(
matrix[index][index]
);
}1
5
9Array of Strings
String[] languages = {
"Java",
"Python",
"JavaScript",
"C++"
};
for (String language : languages) {
System.out.println(language);
}Array of Objects
An object array stores references to objects.
String[] names =
new String[3];
names[0] = "Aarav";
names[1] = "Riya";
names[2] = "Kabir";names ARRAY
┌─────────────┐
│ Reference │──────► "Aarav"
├─────────────┤
│ Reference │──────► "Riya"
├─────────────┤
│ Reference │──────► "Kabir"
└─────────────┘Primitive vs Object Arrays
PRIMITIVE ARRAY
int[] numbers
Stores primitive values directly
[10] [20] [30]
OBJECT ARRAY
String[] names
Stores object references
[ref] [ref] [ref]Duplicate Elements
int[] numbers = {
10, 20, 30, 20, 40, 10
};
for (
int first = 0;
first < numbers.length;
first++
) {
for (
int second = first + 1;
second < numbers.length;
second++
) {
if (
numbers[first]
== numbers[second]
) {
System.out.println(
numbers[first]
);
break;
}
}
}Remove Duplicates
int[] numbers = {
10, 10, 20, 20, 30, 40, 40
};
int uniqueCount = 1;
for (
int index = 1;
index < numbers.length;
index++
) {
if (
numbers[index]
!= numbers[uniqueCount - 1]
) {
numbers[uniqueCount] =
numbers[index];
uniqueCount++;
}
}
for (
int index = 0;
index < uniqueCount;
index++
) {
System.out.println(
numbers[index]
);
}Second Largest Element
int[] numbers = {
10, 50, 30, 80, 60
};
int largest =
Integer.MIN_VALUE;
int secondLargest =
Integer.MIN_VALUE;
for (int number : numbers) {
if (number > largest) {
secondLargest = largest;
largest = number;
} else if (
number > secondLargest
&& number != largest
) {
secondLargest = number;
}
}
System.out.println(
"Second Largest: "
+ secondLargest
);Frequency of Elements
int[] numbers = {
10, 20, 10, 30, 20, 10
};
boolean[] visited =
new boolean[numbers.length];
for (
int first = 0;
first < numbers.length;
first++
) {
if (visited[first]) {
continue;
}
int count = 1;
for (
int second = first + 1;
second < numbers.length;
second++
) {
if (
numbers[first]
== numbers[second]
) {
count++;
visited[second] = true;
}
}
System.out.println(
numbers[first]
+ " occurs "
+ count
+ " times"
);
}Merge Two Arrays
int[] first = {
10, 20, 30
};
int[] second = {
40, 50
};
int[] merged =
new int[
first.length
+ second.length
];
System.arraycopy(
first,
0,
merged,
0,
first.length
);
System.arraycopy(
second,
0,
merged,
first.length,
second.length
);Rotate Array
int[] numbers = {
10, 20, 30, 40, 50
};
int first =
numbers[0];
for (
int index = 0;
index < numbers.length - 1;
index++
) {
numbers[index] =
numbers[index + 1];
}
numbers[numbers.length - 1] =
first;[20, 30, 40, 50, 10]Common Array Errors
ARRAY ERRORS
├── Forgetting Array Brackets
├── Using Wrong Element Type
├── Using Negative Array Size
├── Accessing Negative Index
├── Accessing Index Equal to length
├── Accessing Index Greater than Last Index
├── Starting Loop at 1
├── Using <= Instead of <
├── Forgetting Zero-Based Indexing
├── Using length() Instead of length
├── Printing Array Reference Directly
├── Comparing Arrays with ==
├── Confusing Reference Copy with Element Copy
├── Modifying Shared Array Unexpectedly
├── Accessing null Array
├── Assuming Array Size Can Change
├── Forgetting Default Values
├── Using Uninitialized Object Elements
├── Dividing by Empty Array Length
├── Reading First Element of Empty Array
├── Binary Searching Unsorted Data
├── Incorrect Binary Search Boundaries
├── Incorrect Bubble Sort Boundaries
├── Forgetting to Reset Temporary Variables
├── Incorrect Reverse Loop Condition
├── Wrong Source or Destination Index
├── Invalid Copy Range
├── Assuming clone Performs Deep Copy
├── Assuming 2D Arrays are Always Rectangular
├── Using matrix[0].length on Empty Matrix
├── Wrong Row Index
├── Wrong Column Index
├── Incorrect Nested Loop Boundaries
├── Ignoring Jagged Row Lengths
├── Confusing Arrays.toString with deepToString
├── Duplicate Output Repeated Multiple Times
├── Incorrect Second Largest Logic
├── Ignoring Duplicate Maximum Values
├── Returning Internal Mutable Array Unexpectedly
└── Using Arrays When Dynamic Size is RequiredBest Practices
- Use meaningful array names.
- Use plural names such as numbers, students, prices, and scores.
- Prefer type[] variable syntax.
- Choose the correct element type.
- Use array literals when values are known in advance.
- Use new when the size is determined at runtime.
- Remember that array size is fixed.
- Use array.length instead of hardcoded sizes.
- Remember that valid indexes start at 0.
- Remember that the last index is length - 1.
- Use index < array.length in forward loops.
- Check indexes before accessing elements.
- Handle empty arrays when necessary.
- Do not access array[0] without ensuring the array is not empty.
- Check for null before accessing uncertain array references.
- Use enhanced for loops when indexes are unnecessary.
- Use traditional for loops when indexes are needed.
- Use traditional loops when modifying elements by position.
- Use reverse loops carefully.
- Use Arrays.toString for one-dimensional array output.
- Use Arrays.deepToString for nested arrays.
- Import java.util.Arrays when using Arrays utility methods.
- Initialize maximum and minimum values carefully.
- For non-empty arrays, initialize maximum and minimum from the first element.
- Avoid using arbitrary initial maximum or minimum values.
- Use a wider numeric type for sums when overflow is possible.
- Cast before division when calculating decimal averages.
- Use linear search for unsorted or small arrays.
- Use binary search only with sorted arrays.
- Use Arrays.sort for standard sorting requirements.
- Implement sorting algorithms manually for learning purposes.
- Do not use == to compare array contents.
- Use Arrays.equals for one-dimensional content comparison.
- Understand the difference between reference copying and array copying.
- Use clone for simple shallow array copies.
- Use Arrays.copyOf when changing copy length.
- Use Arrays.copyOfRange for copying ranges.
- Use System.arraycopy for efficient controlled copying.
- Validate source and destination ranges.
- Remember that object array copies are usually shallow.
- Avoid unexpected modification of shared arrays.
- Document methods that modify array arguments.
- Create a copy before modification when the original must remain unchanged.
- Use helper methods for repeated array operations.
- Keep array-processing methods focused.
- Validate method parameters.
- Return empty arrays instead of null when appropriate.
- Be careful when exposing mutable internal arrays.
- Remember that Java multidimensional arrays are arrays of arrays.
- Use matrix.length for row count.
- Use matrix[row].length for each row length.
- Support jagged arrays when appropriate.
- Do not assume all rows have equal length.
- Use nested loops for multidimensional traversal.
- Use descriptive row and column variable names.
- Check matrix dimensions before matrix operations.
- Ensure matrices have compatible dimensions before addition.
- Use correct dimensions when creating transpose matrices.
- Handle duplicate values carefully.
- Define what second largest means when duplicates exist.
- Test algorithms with empty arrays.
- Test arrays containing one element.
- Test arrays containing duplicate values.
- Test already sorted arrays.
- Test reverse-sorted arrays.
- Test arrays containing negative values.
- Test arrays containing zero.
- Test arrays containing maximum and minimum numeric values.
- Prefer clarity over clever array tricks.
- Use collections when dynamic resizing is required.
Array Selection Guide
MULTIPLE RELATED VALUES?
│
├── NO ──────► USE NORMAL VARIABLES
│
└── YES
│
▼
SAME DATA TYPE?
│
├── NO ──────► CONSIDER OBJECTS
│
└── YES
│
▼
FIXED SIZE?
│
├── YES ─────► ARRAY
│
└── NO ──────► CONSIDER COLLECTIONS
TABULAR OR GRID DATA?
│
├── YES ─────► 2D ARRAY
│
└── NO ──────► 1D ARRAY
ROWS HAVE DIFFERENT LENGTHS?
│
├── YES ─────► JAGGED ARRAY
│
└── NO ──────► RECTANGULAR 2D ARRAYArray Checklist
ARRAY CHECKLIST
[ ] Array has a meaningful plural name
[ ] Correct element type is selected
[ ] Array size is appropriate
[ ] Fixed-size behavior is acceptable
[ ] Array is initialized before use
[ ] null is handled when necessary
[ ] Zero-based indexing is remembered
[ ] First valid index is 0
[ ] Last valid index is length - 1
[ ] Loop uses index < array.length
[ ] Empty arrays are handled
[ ] array[0] is not accessed blindly
[ ] array.length is used instead of hardcoded size
[ ] Correct loop type is selected
[ ] Enhanced for is used when index is unnecessary
[ ] Traditional for is used when index is required
[ ] Reverse traversal starts at length - 1
[ ] Array output uses appropriate formatting
[ ] Arrays.toString is used for 1D arrays
[ ] Arrays.deepToString is used for nested arrays
[ ] Sum calculation considers overflow
[ ] Average uses decimal division when needed
[ ] Maximum logic handles negative values
[ ] Minimum logic handles positive values
[ ] Search algorithm matches data conditions
[ ] Binary search data is sorted
[ ] Sort boundaries are correct
[ ] Array content comparison does not use ==
[ ] Reference copy and element copy are distinguished
[ ] Shared arrays are not modified unexpectedly
[ ] Copy method matches the requirement
[ ] Copy ranges are valid
[ ] Object array shallow-copy behavior is understood
[ ] Method modifications are intentional
[ ] Returned mutable arrays are handled carefully
[ ] 2D row count uses matrix.length
[ ] Column count uses matrix[row].length
[ ] Jagged arrays are handled correctly
[ ] Nested loop boundaries use current row length
[ ] Matrix dimensions are compatible
[ ] Duplicate handling is defined
[ ] One-element arrays are tested
[ ] Empty arrays are tested
[ ] Duplicate values are tested
[ ] Negative values are tested
[ ] Boundary values are tested
[ ] Collection is considered when dynamic size is requiredCommon Misconceptions
- The first array index is 0, not 1.
- The last index is length - 1.
- An index equal to length is invalid.
- Array size cannot change after creation.
- The array variable stores a reference.
- Arrays are objects in Java.
- Array elements receive default values.
- Local array variables do not automatically receive references.
- array.length is a field, not a method.
- String length() and array length are different.
- Printing an array directly does not normally print its elements.
- The == operator compares array references.
- Arrays.equals compares one-dimensional array contents.
- Assigning one array variable to another does not copy elements.
- A reference copy makes both variables point to the same array.
- clone creates a new array object.
- Copies of object arrays are generally shallow.
- Enhanced for loops do not provide direct index access.
- Changing the enhanced-for loop variable does not replace primitive array elements.
- Binary search requires sorted data.
- Arrays.sort modifies the original array.
- Arrays.copyOf can create a larger or smaller array.
- Arrays.copyOfRange excludes the ending index.
- Multidimensional arrays are arrays of arrays.
- 2D arrays do not have to be rectangular.
- Each row of a jagged array can have a different length.
- matrix.length gives the number of rows.
- matrix[row].length gives the length of a specific row.
- Arrays.deepToString is useful for nested arrays.
- Passing an array to a method passes a copy of the reference value.
- A method can modify the same array object through the copied reference.
- Reassigning a method parameter does not reassign the caller variable.
- Arrays are useful for fixed-size collections.
- Collections are often better when the number of elements changes frequently.
Practice Exercises
- Create an array containing five integers.
- Print the first element.
- Print the last element.
- Print the array length.
- Modify the middle element.
- Ask the user for array size.
- Create the array.
- Accept every element from the user.
- Display all elements.
- Create an integer array.
- Calculate the sum.
- Calculate the decimal average.
- Display both results.
- Find the largest value.
- Find the smallest value.
- Do not use Arrays.sort.
- Test with negative numbers.
- Accept a target value.
- Search using linear search.
- Display the index when found.
- Display a message when not found.
- Reverse an array without creating another array.
- Use two indexes.
- Swap elements from both ends.
- Display the final array.
- Implement bubble sort.
- Sort values in ascending order.
- Modify the solution for descending order.
- Compare the result with Arrays.sort.
- Find duplicate values.
- Avoid printing the same duplicate repeatedly.
- Count the frequency of each value.
- Test with multiple repeated values.
- Create a 3 × 3 matrix.
- Accept values from the user.
- Display the matrix.
- Calculate the sum of all elements.
- Display the main diagonal.
- Create methods for sum, average, maximum, and minimum.
- Create a method for linear search.
- Create a method for reversing an array.
- Keep the main method focused on testing.
Common Interview Questions
What is an array in Java?
An array is a fixed-size object that stores multiple values of the same declared type.
What is the first index of an array?
The first index is 0.
What is the last valid index?
The last valid index is array.length - 1.
Can the size of an array change?
No. The size is fixed after the array object is created.
Are arrays objects in Java?
Yes. Arrays are objects.
What happens when an invalid index is accessed?
Java throws ArrayIndexOutOfBoundsException.
What is the difference between array.length and String.length()?
Array length is a field, while String length() is a method.
What does assigning one array variable to another do?
It copies the reference value, so both variables refer to the same array object.
How can array contents be compared?
Arrays.equals can compare one-dimensional array contents.
What is a jagged array?
A jagged array is a multidimensional array whose rows have different lengths.
What is the difference between linear and binary search?
Linear search checks elements sequentially, while binary search repeatedly halves a sorted search range.
Why must binary search use sorted data?
Binary search decides which half to discard based on ordering, so unsorted data breaks that logic.
What is a shallow array copy?
A shallow copy creates a new array but copies object references rather than duplicating the referenced objects.
Can arrays be passed to methods?
Yes. A copy of the array reference value is passed to the method.
Can a method return an array?
Yes. An array reference can be returned from a method.
Frequently Asked Questions
When should I use an array?
Use an array when you need a fixed-size collection of values with the same declared type.
Can an array contain different data types?
An array has one declared element type. Object arrays can store references to compatible object types.
Can an array be empty?
Yes. An array can have a length of zero.
Can an array be null?
Yes. An array reference variable can contain null.
Can I resize an existing array?
No. You must create another array or use a dynamic collection such as ArrayList.
Should I use for or enhanced for?
Use enhanced for when you only need element values. Use a traditional for loop when you need indexes or positional modification.
Why does printing an array directly show strange text?
The default object representation is being printed instead of the elements. Use Arrays.toString or Arrays.deepToString.
Does Arrays.sort create a new array?
No. It sorts the supplied array itself.
Can a 2D array have rows of different sizes?
Yes. Java supports jagged arrays.
What should I learn after arrays?
The next lesson covers Strings in Java.
Key Takeaways
- Arrays store multiple values under one variable name.
- All array elements use the same declared type.
- Arrays have a fixed size.
- Arrays use zero-based indexing.
- The first index is 0.
- The last index is length - 1.
- Arrays are objects in Java.
- Array variables store references.
- Arrays can store primitive values.
- Arrays can store object references.
- Array elements receive default values.
- Arrays are created using new or array literals.
- Array length is accessed using the length field.
- array.length is not a method.
- Invalid indexes cause ArrayIndexOutOfBoundsException.
- Arrays can be traversed using loops.
- Traditional for loops provide index access.
- Enhanced for loops provide direct element access.
- while and do-while loops can traverse arrays.
- Arrays can be traversed in reverse.
- Array size can be determined at runtime.
- Array size cannot change after creation.
- Arrays.toString prints one-dimensional arrays.
- Arrays.deepToString prints nested arrays.
- Loops can calculate sum and average.
- Maximum and minimum values can be found by traversal.
- Linear search works with unsorted arrays.
- Binary search requires sorted arrays.
- Arrays.binarySearch provides built-in binary search.
- Arrays.sort sorts arrays.
- Bubble sort is a basic comparison-based sorting algorithm.
- Arrays can be reversed by swapping elements.
- Assigning one array variable to another copies the reference.
- Reference copying does not duplicate elements.
- clone creates a separate array object.
- Arrays.copyOf creates a copy with a specified length.
- Arrays.copyOfRange copies part of an array.
- System.arraycopy efficiently copies elements.
- The == operator compares array references.
- Arrays.equals compares one-dimensional contents.
- Arrays.fill assigns the same value to elements.
- Array references can contain null.
- Accessing a null array causes NullPointerException.
- Anonymous arrays can be created without named variables.
- Arrays can be passed to methods.
- Methods can modify array objects.
- Arrays can be returned from methods.
- One-dimensional arrays use one index.
- Two-dimensional arrays use row and column indexes.
- Java multidimensional arrays are arrays of arrays.
- matrix.length gives the row count.
- matrix[row].length gives a specific row length.
- Jagged arrays have rows of different lengths.
- Three-dimensional arrays are possible.
- Matrices can be represented using 2D arrays.
- Arrays can store strings.
- Arrays can store object references.
- Duplicate elements can be detected.
- Element frequencies can be counted.
- Arrays can be merged.
- Arrays can be rotated.
- Arrays are fundamental to searching and sorting algorithms.
- Arrays are best suited for fixed-size collections.
- Dynamic collections are better when size changes frequently.
Summary
Arrays allow Java programs to store and process multiple related values using a single variable name. Instead of creating a separate variable for every value, an array organizes elements into indexed positions.
Java arrays use zero-based indexing. The first element is stored at index 0, and the last valid index is always array.length - 1. Accessing an invalid index causes ArrayIndexOutOfBoundsException.
Arrays can be created using the new keyword or initialized directly using array literals. When created with new, array elements automatically receive default values based on their type.
Loops make arrays powerful by allowing programs to traverse, search, modify, count, sum, compare, and analyze elements efficiently. Traditional for loops provide index control, while enhanced for loops provide simpler element-based traversal.
The java.util.Arrays utility class provides useful methods for printing, sorting, searching, comparing, copying, and filling arrays.
Arrays are objects in Java. Array variables store references, which means assigning one array variable to another makes both variables refer to the same array. A true copy requires creating another array object.
Arrays can be passed to methods and returned from methods. Because Java passes a copy of the array reference value, a method can modify the same array object through that copied reference.
Multidimensional arrays allow programs to represent tables, grids, matrices, and more complex structures. Java implements multidimensional arrays as arrays of arrays, which also allows jagged structures with rows of different lengths.
Mastering arrays is essential because they form the foundation of searching algorithms, sorting algorithms, matrices, collections, data structures, and many real-world programming problems.
- You understand what arrays are.
- You understand why arrays are needed.
- You understand how arrays work.
- You know the main characteristics of arrays.
- You can declare arrays.
- You can create arrays.
- You can initialize arrays.
- You can use array literals.
- You understand default values.
- You understand zero-based indexing.
- You can access array elements.
- You can modify array elements.
- You can use array.length.
- You understand ArrayIndexOutOfBoundsException.
- You can traverse arrays.
- You can use for loops with arrays.
- You can use enhanced for loops.
- You can use while loops.
- You can use do-while loops.
- You can traverse arrays in reverse.
- You can compare traditional and enhanced for loops.
- You can accept array input.
- You can display array output.
- You can use Arrays.toString.
- You can calculate array sums.
- You can calculate array averages.
- You can find maximum values.
- You can find minimum values.
- You can count even and odd values.
- You can count positive, negative, and zero values.
- You understand array searching.
- You can implement linear search.
- You can create reusable search methods.
- You understand binary search.
- You can use Arrays.binarySearch.
- You understand array sorting.
- You can implement bubble sort.
- You can use Arrays.sort.
- You can partially sort arrays.
- You can reverse arrays.
- You understand array copying.
- You understand reference copying.
- You can manually copy arrays.
- You can use clone.
- You can use Arrays.copyOf.
- You can use Arrays.copyOfRange.
- You can use System.arraycopy.
- You understand array comparison.
- You can use Arrays.equals.
- You can fill arrays.
- You can use Arrays.fill.
- You understand that arrays are objects.
- You understand array references.
- You understand null arrays.
- You can use anonymous arrays.
- You can pass arrays to methods.
- You understand array modification inside methods.
- You can return arrays from methods.
- You understand runtime-sized arrays.
- You understand one-dimensional arrays.
- You understand two-dimensional arrays.
- You can declare 2D arrays.
- You can initialize 2D arrays.
- You can access 2D elements.
- You can traverse 2D arrays.
- You can accept 2D array input.
- You understand rows and columns.
- You can use Arrays.deepToString.
- You understand jagged arrays.
- You understand three-dimensional arrays.
- You understand multidimensional array memory.
- You can add matrices.
- You can transpose matrices.
- You can access diagonal elements.
- You can create String arrays.
- You understand object arrays.
- You can compare primitive and object arrays.
- You can find duplicate elements.
- You can remove duplicates from sorted arrays.
- You can find the second largest element.
- You can calculate element frequencies.
- You can merge arrays.
- You can rotate arrays.
- You can identify common array errors.
- You know array best practices.
- You know when arrays are appropriate.
- You are ready to learn Strings.