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.
Creating Arrays
Section titled “Creating Arrays”// Declarationint[] numbers;
// Initialization with sizenumbers = new int[5];
// Declaration and initialization combinedint[] scores = new int[10];
// Declaration, creation and initialization with valuesString[] names = {"John", "Alice", "Bob"};Accessing Elements
Section titled “Accessing Elements”Array elements are accessed using zero-based indexing:
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elementsint firstNumber = numbers[0]; // 10int thirdNumber = numbers[2]; // 30
// Modifying elementsnumbers[1] = 25; // Changes 20 to 25Array Length
Section titled “Array Length”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); // 3Iterating
Section titled “Iterating”// Using for loopint[] numbers = {1, 2, 3, 4, 5};for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]);}Common Pitfalls
Section titled “Common Pitfalls”- 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)