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
1// Declare and allocate memory for an array of 5 integers2int[] numbers = new int[5];34// Declare and allocate memory for an array of 3 strings5String[] names = new String[3];
2. Declaration, Allocation, and Initialization
1// Declare, allocate, and initialize an array of integers2int[] numbers = new int[] {10, 20, 30, 40, 50};34// Shorthand syntax (only for initialization during declaration)5int[] moreNumbers = {15, 25, 35, 45, 55};67// Declare, allocate, and initialize an array of strings8String[] 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:
1int[] numbers = {10, 20, 30, 40, 50};23// Accessing array elements4System.out.println("First element: " + numbers[0]); // Output: 105System.out.println("Third element: " + numbers[2]); // Output: 306System.out.println("Last element: " + numbers[4]); // Output: 5078// Modifying array elements9numbers[1] = 25; // Change the second element10System.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
.
int[] numbers = {10, 20, 30};// This will throw an ArrayIndexOutOfBoundsExceptionSystem.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:
1int[] numbers = {10, 20, 30, 40, 50};2System.out.println("Array length: " + numbers.length); // Output: 534String[] 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:
1import java.util.Arrays;23public class ArrayUtilityExample {4 public static void main(String[] args) {5 int[] numbers = {5, 2, 9, 1, 7};67 // toString() - Convert array to string representation8 System.out.println("Array: " + Arrays.toString(numbers));9 // Output: Array: [5, 2, 9, 1, 7]1011 // sort() - Sort array in ascending order12 Arrays.sort(numbers);13 System.out.println("Sorted array: " + Arrays.toString(numbers));14 // Output: Sorted array: [1, 2, 5, 7, 9]1516 // binarySearch() - Find element in sorted array17 int index = Arrays.binarySearch(numbers, 5);18 System.out.println("Index of 5: " + index);19 // Output: Index of 5: 22021 // fill() - Fill array with a specific value22 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]2627 // equals() - Compare two arrays28 int[] array1 = {1, 2, 3};29 int[] array2 = {1, 2, 3};30 int[] array3 = {1, 2, 4};3132 System.out.println("array1 equals array2: " + Arrays.equals(array1, array2));33 // Output: array1 equals array2: true3435 System.out.println("array1 equals array3: " + Arrays.equals(array1, array3));36 // Output: array1 equals array3: false3738 // copyOf() - Create a copy of an array39 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]4344 // copyOfRange() - Copy a range of elements45 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
1int[] numbers = {10, 20, 30, 40, 50};23// Standard for loop4for (int i = 0; i < numbers.length; i++) {5 System.out.println("Element at index " + i + ": " + numbers[i]);6}78// Output:9// Element at index 0: 1010// Element at index 1: 2011// Element at index 2: 3012// Element at index 3: 4013// Element at index 4: 50
2. Using an Enhanced for Loop (for-each)
1int[] numbers = {10, 20, 30, 40, 50};23// Enhanced for loop (for-each)4for (int number : numbers) {5 System.out.println("Element: " + number);6}78// Output:9// Element: 1010// Element: 2011// Element: 3012// Element: 4013// 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:
1// Declare and initialize a 2D array (3x3 matrix)2int[][] matrix = {3 {1, 2, 3},4 {4, 5, 6},5 {7, 8, 9}6};78// Access elements9System.out.println("Element at row 0, column 0: " + matrix[0][0]); // Output: 110System.out.println("Element at row 1, column 2: " + matrix[1][2]); // Output: 61112// Iterate through a 2D array using nested loops13for (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}1920// Output:21// 1 2 322// 4 5 623// 7 8 92425// Using enhanced for loop26for (int[] row : matrix) {27 for (int element : row) {28 System.out.print(element + " ");29 }30 System.out.println();31}3233// Output is the same as above
Jagged Arrays
In Java, multi-dimensional arrays can have different lengths for each row (jagged arrays):
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];67// Initialize the jagged array8jaggedArray[0][0] = 1;9jaggedArray[0][1] = 2;1011jaggedArray[1][0] = 3;12jaggedArray[1][1] = 4;13jaggedArray[1][2] = 5;14jaggedArray[1][3] = 6;1516jaggedArray[2][0] = 7;17jaggedArray[2][1] = 8;18jaggedArray[2][2] = 9;1920// Alternatively, initialize using array literals21int[][] anotherJaggedArray = {22 {1, 2},23 {3, 4, 5, 6},24 {7, 8, 9}25};2627// Iterate through a jagged array28for (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}3435// Output:36// 1 237// 3 4 5 638// 7 8 9
Common Array Operations
Finding the Maximum and Minimum Values
1int[] numbers = {5, 8, 2, 10, 3, 1, 7};23// Find maximum value4int max = numbers[0]; // Assume first element is the maximum5for (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: 101112// Find minimum value13int min = numbers[0]; // Assume first element is the minimum14for (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
1int[] numbers = {5, 8, 2, 10, 3, 1, 7};23// Calculate sum4int sum = 0;5for (int number : numbers) {6 sum += number;7}8System.out.println("Sum: " + sum); // Output: 36910// Calculate average11double average = (double) sum / numbers.length;12System.out.println("Average: " + average); // Output: 5.142857142857143
Searching for an Element
1int[] numbers = {5, 8, 2, 10, 3, 1, 7};2int searchValue = 3;34// Linear search5int 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 found10 }11}1213if (index != -1) {14 System.out.println(searchValue + " found at index " + index);15} else {16 System.out.println(searchValue + " not found in the array");17}1819// Output: 3 found at index 4
Reversing an Array
1int[] numbers = {1, 2, 3, 4, 5};23// Reverse the array4for (int i = 0; i < numbers.length / 2; i++) {5 // Swap elements6 int temp = numbers[i];7 numbers[i] = numbers[numbers.length - 1 - i];8 numbers[numbers.length - 1 - i] = temp;9}1011// Print the reversed array12System.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:
1public class ArrayMethodsExample {2 public static void main(String[] args) {3 int[] numbers = {1, 2, 3, 4, 5};45 // Pass array to method6 System.out.println("Sum: " + calculateSum(numbers));78 // Modify array in method9 doubleValues(numbers);1011 System.out.print("Modified array: ");12 for (int number : numbers) {13 System.out.print(number + " ");14 }15 System.out.println();1617 // Get array from method18 int[] evenNumbers = getEvenNumbers(10);1920 System.out.print("Even numbers: ");21 for (int number : evenNumbers) {22 System.out.print(number + " ");23 }24 }2526 // Method that takes an array as parameter27 public static int calculateSum(int[] array) {28 int sum = 0;29 for (int value : array) {30 sum += value;31 }32 return sum;33 }3435 // Method that modifies an array36 public static void doubleValues(int[] array) {37 for (int i = 0; i < array.length; i++) {38 array[i] *= 2;39 }40 }4142 // Method that returns an array43 public static int[] getEvenNumbers(int n) {44 int[] result = new int[n / 2];4546 for (int i = 0; i < result.length; i++) {47 result[i] = (i + 1) * 2;48 }4950 return result;51 }52}5354// Output:55// Sum: 1556// Modified array: 2 4 6 8 1057// 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:
1import java.util.Arrays;23public class StudentGradesAnalyzer {4 public static void main(String[] args) {5 // Student names6 String[] students = {"Alice", "Bob", "Charlie", "David", "Eve"};78 // Student grades for three subjects: Math, Science, English9 int[][] grades = {10 {85, 90, 78}, // Alice's grades11 {70, 65, 80}, // Bob's grades12 {95, 92, 88}, // Charlie's grades13 {60, 75, 70}, // David's grades14 {88, 84, 90} // Eve's grades15 };1617 // Calculate and display each student's average grade18 System.out.println("Student Average Grades:");19 System.out.println("----------------------");2021 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 }2526 System.out.println();2728 // Find the student with the highest average29 int topStudentIndex = findTopStudent(grades);30 System.out.println("Top student: " + students[topStudentIndex]);3132 System.out.println();3334 // Calculate and display subject averages35 String[] subjects = {"Math", "Science", "English"};36 double[] subjectAverages = calculateSubjectAverages(grades);3738 System.out.println("Subject Averages:");39 System.out.println("----------------");4041 for (int i = 0; i < subjects.length; i++) {42 System.out.printf("%s: %.2f%n", subjects[i], subjectAverages[i]);43 }44 }4546 // Calculate average grade for a student47 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 }5455 // Find the index of the student with the highest average56 public static int findTopStudent(int[][] grades) {57 double maxAverage = 0;58 int topStudentIndex = 0;5960 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 }6768 return topStudentIndex;69 }7071 // Calculate average grade for each subject72 public static double[] calculateSubjectAverages(int[][] grades) {73 // Assuming all students have the same number of subjects74 int numSubjects = grades[0].length;75 double[] subjectAverages = new double[numSubjects];7677 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 }8485 return subjectAverages;86 }87}8889// Output:90// Student Average Grades:91// ----------------------92// Alice: 84.3393// Bob: 71.6794// Charlie: 91.6795// David: 68.3396// Eve: 87.3397//98// Top student: Charlie99//100// Subject Averages:101// ----------------102// Math: 79.60103// Science: 81.20104// English: 81.20
Practice Exercises
- Create a program that finds the second largest element in an array.
- Write a method that merges two sorted arrays into a single sorted array.
- Create a program that removes duplicate elements from an array.
- Write a method that rotates the elements of an array to the right by a specified number of positions.
- 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 moreUnderstand the fundamentals of OOP in Java.
Learn moreLearn about Java Collections Framework.
Learn more