Progress7 of 14 topics

50% complete

Java Arrays

Arrays are one of the most fundamental data structures in Java, allowing you to store multiple values of the same type. In this tutorial, you'll learn how to create, access, and manipulate arrays in Java with practical examples.

What is an Array?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created, and its length is fixed after creation.

Think of an array as a row of boxes, where each box can hold one item. All boxes must contain the same type of item, and you can access each box using its position number (index).

Creating Arrays

There are several ways to create arrays in Java:

1. Declaration and Allocation

java
1// Declare and allocate memory for an array of 5 integers
2int[] numbers = new int[5];
3
4// Declare and allocate memory for an array of 3 strings
5String[] names = new String[3];

2. Declaration, Allocation, and Initialization

java
1// Declare, allocate, and initialize an array of integers
2int[] numbers = new int[] {10, 20, 30, 40, 50};
3
4// Shorthand syntax (only for initialization during declaration)
5int[] moreNumbers = {15, 25, 35, 45, 55};
6
7// Declare, allocate, and initialize an array of strings
8String[] fruits = {"Apple", "Banana", "Orange"};

Array Declaration Styles:

Java allows two styles for declaring arrays:

  • int[] numbers; (Preferred style)
  • int numbers[]; (C/C++ style)

The first style is preferred as it clearly indicates that the variable is an array of integers.

Accessing Array Elements

Array elements are accessed using their index. In Java, array indices start at 0.

Index positions in an array:

10
20
30
40
50
0
1
2
3
4
java
1int[] numbers = {10, 20, 30, 40, 50};
2
3// Accessing array elements
4System.out.println("First element: " + numbers[0]); // Output: 10
5System.out.println("Third element: " + numbers[2]); // Output: 30
6System.out.println("Last element: " + numbers[4]); // Output: 50
7
8// Modifying array elements
9numbers[1] = 25; // Change the second element
10System.out.println("Modified second element: " + numbers[1]); // Output: 25

Warning: ArrayIndexOutOfBoundsException

If you try to access an array element with an index that is negative or greater than or equal to the array's length, Java will throw an ArrayIndexOutOfBoundsException.

java
int[] numbers = {10, 20, 30};
// This will throw an ArrayIndexOutOfBoundsException
System.out.println(numbers[3]); // Error! Index 3 is out of bounds

Array Properties and Methods

Array Length

The length of an array is available through the length property:

java
1int[] numbers = {10, 20, 30, 40, 50};
2System.out.println("Array length: " + numbers.length); // Output: 5
3
4String[] names = new String[3];
5System.out.println("Array length: " + names.length); // Output: 3

Array Utility Methods

The java.util.Arrays class provides many useful methods for working with arrays:

java
1import java.util.Arrays;
2
3public class ArrayUtilityExample {
4 public static void main(String[] args) {
5 int[] numbers = {5, 2, 9, 1, 7};
6
7 // toString() - Convert array to string representation
8 System.out.println("Array: " + Arrays.toString(numbers));
9 // Output: Array: [5, 2, 9, 1, 7]
10
11 // sort() - Sort array in ascending order
12 Arrays.sort(numbers);
13 System.out.println("Sorted array: " + Arrays.toString(numbers));
14 // Output: Sorted array: [1, 2, 5, 7, 9]
15
16 // binarySearch() - Find element in sorted array
17 int index = Arrays.binarySearch(numbers, 5);
18 System.out.println("Index of 5: " + index);
19 // Output: Index of 5: 2
20
21 // fill() - Fill array with a specific value
22 int[] filledArray = new int[5];
23 Arrays.fill(filledArray, 10);
24 System.out.println("Filled array: " + Arrays.toString(filledArray));
25 // Output: Filled array: [10, 10, 10, 10, 10]
26
27 // equals() - Compare two arrays
28 int[] array1 = {1, 2, 3};
29 int[] array2 = {1, 2, 3};
30 int[] array3 = {1, 2, 4};
31
32 System.out.println("array1 equals array2: " + Arrays.equals(array1, array2));
33 // Output: array1 equals array2: true
34
35 System.out.println("array1 equals array3: " + Arrays.equals(array1, array3));
36 // Output: array1 equals array3: false
37
38 // copyOf() - Create a copy of an array
39 int[] originalArray = {1, 2, 3, 4, 5};
40 int[] copiedArray = Arrays.copyOf(originalArray, originalArray.length);
41 System.out.println("Copied array: " + Arrays.toString(copiedArray));
42 // Output: Copied array: [1, 2, 3, 4, 5]
43
44 // copyOfRange() - Copy a range of elements
45 int[] partialCopy = Arrays.copyOfRange(originalArray, 1, 4);
46 System.out.println("Partial copy: " + Arrays.toString(partialCopy));
47 // Output: Partial copy: [2, 3, 4]
48 }
49}

Iterating Through Arrays

There are several ways to iterate through an array in Java:

1. Using a for Loop

java
1int[] numbers = {10, 20, 30, 40, 50};
2
3// Standard for loop
4for (int i = 0; i < numbers.length; i++) {
5 System.out.println("Element at index " + i + ": " + numbers[i]);
6}
7
8// Output:
9// Element at index 0: 10
10// Element at index 1: 20
11// Element at index 2: 30
12// Element at index 3: 40
13// Element at index 4: 50

2. Using an Enhanced for Loop (for-each)

java
1int[] numbers = {10, 20, 30, 40, 50};
2
3// Enhanced for loop (for-each)
4for (int number : numbers) {
5 System.out.println("Element: " + number);
6}
7
8// Output:
9// Element: 10
10// Element: 20
11// Element: 30
12// Element: 40
13// Element: 50

When to Use Each Loop Type:

Standard for loop: Use when you need the index of elements or need to modify array elements.

Enhanced for loop (for-each): Use when you only need to access elements and don't need the index. This loop is more concise and less prone to errors, but you cannot modify the array elements with it.

Multi-dimensional Arrays

Java supports multi-dimensional arrays, which are essentially arrays of arrays.

Two-dimensional Arrays

A two-dimensional array is an array of arrays, often used to represent tables, matrices, or grids:

java
1// Declare and initialize a 2D array (3x3 matrix)
2int[][] matrix = {
3 {1, 2, 3},
4 {4, 5, 6},
5 {7, 8, 9}
6};
7
8// Access elements
9System.out.println("Element at row 0, column 0: " + matrix[0][0]); // Output: 1
10System.out.println("Element at row 1, column 2: " + matrix[1][2]); // Output: 6
11
12// Iterate through a 2D array using nested loops
13for (int i = 0; i < matrix.length; i++) {
14 for (int j = 0; j < matrix[i].length; j++) {
15 System.out.print(matrix[i][j] + " ");
16 }
17 System.out.println();
18}
19
20// Output:
21// 1 2 3
22// 4 5 6
23// 7 8 9
24
25// Using enhanced for loop
26for (int[] row : matrix) {
27 for (int element : row) {
28 System.out.print(element + " ");
29 }
30 System.out.println();
31}
32
33// Output is the same as above

Jagged Arrays

In Java, multi-dimensional arrays can have different lengths for each row (jagged arrays):

java
1// Create a jagged array (different length for each row)
2int[][] jaggedArray = new int[3][];
3jaggedArray[0] = new int[2];
4jaggedArray[1] = new int[4];
5jaggedArray[2] = new int[3];
6
7// Initialize the jagged array
8jaggedArray[0][0] = 1;
9jaggedArray[0][1] = 2;
10
11jaggedArray[1][0] = 3;
12jaggedArray[1][1] = 4;
13jaggedArray[1][2] = 5;
14jaggedArray[1][3] = 6;
15
16jaggedArray[2][0] = 7;
17jaggedArray[2][1] = 8;
18jaggedArray[2][2] = 9;
19
20// Alternatively, initialize using array literals
21int[][] anotherJaggedArray = {
22 {1, 2},
23 {3, 4, 5, 6},
24 {7, 8, 9}
25};
26
27// Iterate through a jagged array
28for (int i = 0; i < jaggedArray.length; i++) {
29 for (int j = 0; j < jaggedArray[i].length; j++) {
30 System.out.print(jaggedArray[i][j] + " ");
31 }
32 System.out.println();
33}
34
35// Output:
36// 1 2
37// 3 4 5 6
38// 7 8 9

Common Array Operations

Finding the Maximum and Minimum Values

java
1int[] numbers = {5, 8, 2, 10, 3, 1, 7};
2
3// Find maximum value
4int max = numbers[0]; // Assume first element is the maximum
5for (int i = 1; i < numbers.length; i++) {
6 if (numbers[i] > max) {
7 max = numbers[i];
8 }
9}
10System.out.println("Maximum value: " + max); // Output: 10
11
12// Find minimum value
13int min = numbers[0]; // Assume first element is the minimum
14for (int i = 1; i < numbers.length; i++) {
15 if (numbers[i] < min) {
16 min = numbers[i];
17 }
18}
19System.out.println("Minimum value: " + min); // Output: 1

Calculating the Sum and Average

java
1int[] numbers = {5, 8, 2, 10, 3, 1, 7};
2
3// Calculate sum
4int sum = 0;
5for (int number : numbers) {
6 sum += number;
7}
8System.out.println("Sum: " + sum); // Output: 36
9
10// Calculate average
11double average = (double) sum / numbers.length;
12System.out.println("Average: " + average); // Output: 5.142857142857143

Searching for an Element

java
1int[] numbers = {5, 8, 2, 10, 3, 1, 7};
2int searchValue = 3;
3
4// Linear search
5int index = -1; // Initialize to -1 (not found)
6for (int i = 0; i < numbers.length; i++) {
7 if (numbers[i] == searchValue) {
8 index = i;
9 break; // Exit the loop once found
10 }
11}
12
13if (index != -1) {
14 System.out.println(searchValue + " found at index " + index);
15} else {
16 System.out.println(searchValue + " not found in the array");
17}
18
19// Output: 3 found at index 4

Reversing an Array

java
1int[] numbers = {1, 2, 3, 4, 5};
2
3// Reverse the array
4for (int i = 0; i < numbers.length / 2; i++) {
5 // Swap elements
6 int temp = numbers[i];
7 numbers[i] = numbers[numbers.length - 1 - i];
8 numbers[numbers.length - 1 - i] = temp;
9}
10
11// Print the reversed array
12System.out.print("Reversed array: ");
13for (int number : numbers) {
14 System.out.print(number + " ");
15}
16// Output: Reversed array: 5 4 3 2 1

Arrays as Method Parameters and Return Values

Arrays can be passed to methods and returned from methods:

java
1public class ArrayMethodsExample {
2 public static void main(String[] args) {
3 int[] numbers = {1, 2, 3, 4, 5};
4
5 // Pass array to method
6 System.out.println("Sum: " + calculateSum(numbers));
7
8 // Modify array in method
9 doubleValues(numbers);
10
11 System.out.print("Modified array: ");
12 for (int number : numbers) {
13 System.out.print(number + " ");
14 }
15 System.out.println();
16
17 // Get array from method
18 int[] evenNumbers = getEvenNumbers(10);
19
20 System.out.print("Even numbers: ");
21 for (int number : evenNumbers) {
22 System.out.print(number + " ");
23 }
24 }
25
26 // Method that takes an array as parameter
27 public static int calculateSum(int[] array) {
28 int sum = 0;
29 for (int value : array) {
30 sum += value;
31 }
32 return sum;
33 }
34
35 // Method that modifies an array
36 public static void doubleValues(int[] array) {
37 for (int i = 0; i < array.length; i++) {
38 array[i] *= 2;
39 }
40 }
41
42 // Method that returns an array
43 public static int[] getEvenNumbers(int n) {
44 int[] result = new int[n / 2];
45
46 for (int i = 0; i < result.length; i++) {
47 result[i] = (i + 1) * 2;
48 }
49
50 return result;
51 }
52}
53
54// Output:
55// Sum: 15
56// Modified array: 2 4 6 8 10
57// Even numbers: 2 4 6 8 10

Important:

In Java, arrays are passed by reference, which means if you modify an array inside a method, the changes will be visible outside the method as well. This is different from primitive types, which are passed by value.

Practical Example: Student Grades Analyzer

Let's create a practical example that uses arrays to store and analyze student grades:

java
1import java.util.Arrays;
2
3public class StudentGradesAnalyzer {
4 public static void main(String[] args) {
5 // Student names
6 String[] students = {"Alice", "Bob", "Charlie", "David", "Eve"};
7
8 // Student grades for three subjects: Math, Science, English
9 int[][] grades = {
10 {85, 90, 78}, // Alice's grades
11 {70, 65, 80}, // Bob's grades
12 {95, 92, 88}, // Charlie's grades
13 {60, 75, 70}, // David's grades
14 {88, 84, 90} // Eve's grades
15 };
16
17 // Calculate and display each student's average grade
18 System.out.println("Student Average Grades:");
19 System.out.println("----------------------");
20
21 for (int i = 0; i < students.length; i++) {
22 double average = calculateAverage(grades[i]);
23 System.out.printf("%s: %.2f%n", students[i], average);
24 }
25
26 System.out.println();
27
28 // Find the student with the highest average
29 int topStudentIndex = findTopStudent(grades);
30 System.out.println("Top student: " + students[topStudentIndex]);
31
32 System.out.println();
33
34 // Calculate and display subject averages
35 String[] subjects = {"Math", "Science", "English"};
36 double[] subjectAverages = calculateSubjectAverages(grades);
37
38 System.out.println("Subject Averages:");
39 System.out.println("----------------");
40
41 for (int i = 0; i < subjects.length; i++) {
42 System.out.printf("%s: %.2f%n", subjects[i], subjectAverages[i]);
43 }
44 }
45
46 // Calculate average grade for a student
47 public static double calculateAverage(int[] grades) {
48 int sum = 0;
49 for (int grade : grades) {
50 sum += grade;
51 }
52 return (double) sum / grades.length;
53 }
54
55 // Find the index of the student with the highest average
56 public static int findTopStudent(int[][] grades) {
57 double maxAverage = 0;
58 int topStudentIndex = 0;
59
60 for (int i = 0; i < grades.length; i++) {
61 double average = calculateAverage(grades[i]);
62 if (average > maxAverage) {
63 maxAverage = average;
64 topStudentIndex = i;
65 }
66 }
67
68 return topStudentIndex;
69 }
70
71 // Calculate average grade for each subject
72 public static double[] calculateSubjectAverages(int[][] grades) {
73 // Assuming all students have the same number of subjects
74 int numSubjects = grades[0].length;
75 double[] subjectAverages = new double[numSubjects];
76
77 for (int subject = 0; subject < numSubjects; subject++) {
78 int sum = 0;
79 for (int student = 0; student < grades.length; student++) {
80 sum += grades[student][subject];
81 }
82 subjectAverages[subject] = (double) sum / grades.length;
83 }
84
85 return subjectAverages;
86 }
87}
88
89// Output:
90// Student Average Grades:
91// ----------------------
92// Alice: 84.33
93// Bob: 71.67
94// Charlie: 91.67
95// David: 68.33
96// Eve: 87.33
97//
98// Top student: Charlie
99//
100// Subject Averages:
101// ----------------
102// Math: 79.60
103// Science: 81.20
104// English: 81.20

Practice Exercises

  1. Create a program that finds the second largest element in an array.
  2. Write a method that merges two sorted arrays into a single sorted array.
  3. Create a program that removes duplicate elements from an array.
  4. Write a method that rotates the elements of an array to the right by a specified number of positions.
  5. Create a program that implements a simple matrix multiplication algorithm using 2D arrays.

Summary

In this tutorial, you've learned:

  • How to create and initialize arrays in Java
  • How to access and modify array elements
  • How to use array properties and utility methods
  • Different ways to iterate through arrays
  • How to work with multi-dimensional arrays
  • Common array operations like finding min/max, calculating sum/average, and searching
  • How to use arrays with methods
  • A practical example of using arrays to analyze student grades

Arrays are a fundamental data structure in Java and are used extensively in programming. Understanding how to work with arrays is essential for developing efficient and organized Java applications. As you continue your Java journey, you'll encounter more advanced data structures that build upon the concepts you've learned here.

Related Tutorials

Learn how to create and use methods in Java.

Learn more

Understand the fundamentals of OOP in Java.

Learn more

Learn about Java Collections Framework.

Learn more