In Java, an array is a container object that holds a fixed number of values of a single type. Think of it as a shelf where you can store and access your books efficiently, rather than scattering them around.
Arrays simplify data management by allowing you to:
Arrays in Java can hold both primitive data types (like int
, double
, boolean
) and objects (like instances of a class). They are indexed starting from 0, making it easy to traverse and access individual elements.
Java allocates a contiguous memory block for arrays, which enhances the efficiency, especially when accessing elements. Here’s how memory allocation works:
int
value contiguously in memory.Let's see how arrays work with some simple Java code:
public class ArraysDemo {
public static void main(String[] args) {
// Creating an array of integers
int[] scores = new int[5];
// Assigning values to the array
scores[0] = 85;
scores[1] = 90;
scores[2] = 95;
scores[3] = 100;
scores[4] = 105;
// Accessing and printing an element from the array
System.out.println("The score of the third student is: " + scores[2]);
}
}
In this example, scores
is an array that stores the scores of five students. We access the score of the third student (index 2 because arrays start at 0) and print it.