Arrays are one of the fundamental building blocks of programming in Java. They provide a way to store multiple values of the same type in a single variable. In this guide, we’ll explore how to declare, initialize, and manipulate arrays in Java with practical examples.
What Is an Array in Java?
An array is a data structure that holds a fixed number of values of a single type. The length of an array is established when the array is created. Arrays in Java are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.
Core Characteristics of Arrays:
Declaring and Initializing Arrays
Declaring an Array
· To declare an array in Java, specify the data type followed by square brackets:
int[] ages; String[] names;
You can initialize an array in two ways:
int[] ages = {10, 25, 30, 451, 5};
int[] ages = new int[5];
Here, the array is created with a size of 5, and all elements are initialized to their default value (0 for integers)
String[] names = new String[10];
Same concept applies here, an array of size 10 is created, all elements are initialized to their default value(null for String)
To access an array use the index:
int[] ages = {10, 20, 30, 40}; System.out.println(ages[0]); // Output: 10 System.out.println(ages[2]); // Output: 30
You can update an array element by assigning a new value:
ages[1] = 25; System.out.println(ages[1]); // Output: 25
Trying to access an index outside the array size will throw an ArrayIndexOutOfBoundsException:
System.out.println(ages[4]); // Error if ages.length < 5
int[] ages = {18, 20, 35, 43, 75}; for (int i = 0; i < ages.length; i++) { System.out.println(ages[i]); }
for (int age : ages) { System.out.println(age); }
int[] ages = {18, 20, 35}; System.out.println(ages.length); // Output: 3
int[] source = {1, 2, 3}; int[] destination = new int[source.length]; System.arraycopy(source, 0, destination, 0, source.length);
import java.util.Arrays; int[] original = {1, 2, 3, 4, 5}; // Copy the entire array int[] copy1 = Arrays.copyOf(original, original.length);
Use Arrays.sort to sort an array:
import java.util.Arrays; int[] ages = {3, 1, 4, 1, 5}; Arrays.sort(ages); System.out.println(Arrays.toString(ages));
Arrays are best suited for situations requiring frequent access or retrieval of elements. However, they are not ideal for scenarios involving frequent insertions due to their fixed size and static structure.
At DevelopersMonk, we share tutorials, tips, and insights on modern programming frameworks like React, Next.js, Spring Boot, and more. Join us on our journey to simplify coding and empower developers worldwide!