Arrays in Java are a fundamental data structure that allows you to store multiple values of the same type in a single variable. They are useful when you want to work with multiple pieces of data that are logically related. This tutorial will cover the basics of arrays in Java, including their declaration, initialization, accessing elements, and common operations.
To declare an array in Java, you specify the type of elements it will hold, followed by square brackets []
, and then the array name.
java1int[] numbers; 2String[] names;
Once an array is declared, you can instantiate it using the new
keyword, followed by the type of elements it will hold, and the number of elements in square brackets.
java1numbers = new int[5]; // An array of 5 integers 2names = new String[10]; // An array of 10 Strings
You can also combine declaration and instantiation in one line:
java1int[] numbers = new int[5]; 2String[] names = new String[10];
Arrays can be initialized when they are declared. You can provide the initial values within curly braces {}
.
java1int[] numbers = {1, 2, 3, 4, 5}; 2String[] names = {"Alice", "Bob", "Charlie"};
Array elements are accessed by their index. In Java, array indices start at 0. To access an element, you use the array name followed by the index in square brackets.
java1int firstNumber = numbers[0]; // Access the first element 2String firstPerson = names[0]; // Access the first element 3 4numbers[3] = 100; // Assign a new value to the fourth element
You can find the size of an array (number of elements it can hold) using the length
property.
java1int arraySize = numbers.length; // This will be 5 for the numbers array
To iterate over an array, you can use a for
loop or an enhanced for
loop (also known as the "for-each" loop).
java1// Using a for loop 2for (int i = 0; i < numbers.length; i++) { 3 System.out.println(numbers[i]); 4} 5 6// Using an enhanced for loop 7for (String name : names) { 8 System.out.println(name); 9}
Java supports multidimensional arrays, which are arrays of arrays.
java1int[][] matrix = new int[3][3]; // A 3x3 integer matrix 2 3matrix[0][0] = 1; 4matrix[1][1] = 2; 5matrix[2][2] = 3; 6 7// Initializing a multidimensional array with values 8int[][] presetMatrix = { 9 {1, 2, 3}, 10 {4, 5, 6}, 11 {7, 8, 9} 12};
Some common operations you might perform on arrays include sorting, searching, and copying.
Arrays.sort()
to sort an array.Arrays.binarySearch()
.Arrays.copyOf()
or System.arraycopy()
.java1import java.util.Arrays; 2 3// Sorting 4Arrays.sort(numbers); 5 6// Searching for the value 4 7int index = Arrays.binarySearch(numbers, 4); 8 9// Copying 10int[] numbersCopy = Arrays.copyOf(numbers, numbers.length);
ArrayList
.Arrays are a basic but powerful feature of the Java language. They provide a way to store and manipulate groups of variables efficiently. Understanding arrays is crucial for any Java developer, as they are used extensively in various programming scenarios.