Skip to content

Arrays

This content is for Java. Switch to the latest version for up-to-date documentation.

Arrays are fixed-size containers that store multiple values of the same type.

// Declaration
int[] numbers;
// Initialization with size
numbers = new int[5];
// Declaration and initialization combined
int[] scores = new int[10];
// Declaration, creation and initialization with values
String[] names = {"John", "Alice", "Bob"};

Array elements are accessed using zero-based indexing:

int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
int firstNumber = numbers[0]; // 10
int thirdNumber = numbers[2]; // 30
// Modifying elements
numbers[1] = 25; // Changes 20 to 25

The length property gives the size of an array:

int[] scores = new int[8];
System.out.println(scores.length); // 8
String[] names = {"John", "Alice", "Bob"};
System.out.println(names.length); // 3
// Using for loop
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
  • Array Index Out of Bounds: Accessing an index outside the array’s valid range
  • NullPointerException: Using an array reference that hasn’t been initialized
  • Fixed Size: Arrays cannot be resized after creation (use ArrayList for resizable collections)
Built with passion by Ngineer Lab