Java arrays are fixed-size data structures that store contiguous blocks of homogeneous data types. Every element in an array occupies an adjacent memory location, enabling efficient index-based access with indices starting from 0. A built-in length property exists for all Java arrays to return their total element count. Atttempting to access an index outside the valid range [0, length-1] triggers an ArrayIndexOutOfBoundsException at runtime.
Array Declaration and Initialization
Java supports two primary array declaration syntaxes: dataType[] arrayIdentifier (the Java-recommended style) and dataType arrayIdentifier[] (originating from C/C++ conventions).
Declaring an array alone only creates a reference variable; no memory is allocated until initialization. Two initialization approaches are available:
- Dynamic initialization: Uses the
newkeyword to allocate memory for a specified number of elements, which are automatically set to their type's default value (0 for numeric primitives,falsefor booleans,nullfor objects).
int[] dynamicArr = new int[5];
boolean flagArr[] = new boolean[3];
- Static initialization: Directly assigns a comma-separated list of values enclosed in curly braces during declaration, inferring the array length from the provided elements.
String[] staticNames = {"Alice", "Bob", "Charlie"};
ArrayList for Dynamic Element Management
Since standard arrays have fixed lengths, Java provides java.util.ArrayList (a resizable collecsion class) for scenarios requiring dynamic insertion, deletion, or modification of elements. As a generic collection, ArrayList stores only reference types; wrapper classes like Integer, Double, or Boolean must be used for primitive data equivalents.
Key ArrayList operations include:
import java.util.ArrayList;
// Instantiate an ArrayList for integers
ArrayList<Integer> intList = new ArrayList<>();
// Append an element
intList.add(42);
// Insert at a specific index
intList.add(0, 17);
// Retrieve an element by index
int firstVal = intList.get(0);
// Remove an element by index
intList.remove(1);
// Get current element count
int currentSize = intList.size();
Enhanced for-Loop
For cleaner iteration over arrays or collections, Java offers the enhanced for-loop (also called a "for-each" loop), which eliminates manual index management. Its syntax is:
for (ElementType variable : iterableObject) {
// Process variable
}
Problem Implementation
Given input n followed by n integers, first output the integers in reverse order, then output elements at even indices of the original array, each set space-separated.
import java.util.Scanner;
public class ArrayProcessor {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int elementCount = inputScanner.nextInt();
int[] mainArray = new int[elementCount];
// Populate the array with input values
for (int idx = 0; idx < elementCount; idx++) {
mainArray[idx] = inputScanner.nextInt();
}
// Print reversed array
for (int reverseIdx = mainArray.length - 1; reverseIdx >= 0; reverseIdx--) {
System.out.print(mainArray[reverseIdx]);
if (reverseIdx != 0) {
System.out.print(" ");
}
}
System.out.println();
// Print even-indexed elements (original order)
for (int stepIdx = 0; stepIdx < mainArray.length; stepIdx += 2) {
System.out.print(mainArray[stepIdx]);
if (stepIdx + 2 < mainArray.length) {
System.out.print(" ");
}
}
inputScanner.close();
}
}