Java Array Basics
What is a Java Array?
In Java, an array is a fundamental data structure that allows you to store multiple elements of the same type in a contiguous memory location. Arrays provide a way to organize and manage collections of data efficiently.
Array Declaration and Initialization
Basic Array Declaration
// Declare an integer array
int[] numbers;
// Declare a string array
String[] names;
Array Initialization Methods
// Method 1: Declare and initialize in one line
int[] scores = {85, 90, 75, 88, 92};
// Method 2: Create array with specific size
int[] ages = new int[5];
// Method 3: Initialize with default values
String[] cities = new String[3];
Array Characteristics
Characteristic |
Description |
Fixed Size |
Arrays have a fixed length once created |
Zero-Indexed |
First element is at index 0 |
Type Specific |
Can only store elements of one data type |
Memory Efficient |
Provides quick access to elements |
Array Memory Representation
graph TD
A[Array Memory] --> B[Index 0]
A --> C[Index 1]
A --> D[Index 2]
A --> E[Index 3]
A --> F[Index n-1]
Common Array Operations
Accessing Elements
int[] numbers = {10, 20, 30, 40, 50};
int firstElement = numbers[0]; // Retrieves 10
int thirdElement = numbers[2]; // Retrieves 30
Modifying Elements
int[] numbers = new int[5];
numbers[0] = 100; // Assigns 100 to first element
numbers[3] = 200; // Assigns 200 to fourth element
Array Length Property
Every array in Java has a built-in length
property that returns the total number of elements:
int[] numbers = {1, 2, 3, 4, 5};
int arraySize = numbers.length; // Returns 5
Best Practices
- Always check array bounds to prevent
ArrayIndexOutOfBoundsException
- Use enhanced for-loop for iterating arrays
- Consider using
ArrayList
for dynamic sizing needs
Example: Complete Array Demonstration
public class ArrayDemo {
public static void main(String[] args) {
// Create and initialize an array
int[] temperatures = {72, 75, 80, 85, 90};
// Print array length
System.out.println("Array length: " + temperatures.length);
// Iterate and print elements
for (int temp : temperatures) {
System.out.println("Temperature: " + temp);
}
}
}
This section provides a comprehensive introduction to Java arrays, covering declaration, initialization, characteristics, and basic operations. LabEx recommends practicing these concepts to build a strong foundation in Java array manipulation.