Array Type Basics
Introduction to Arrays in Java
Arrays are fundamental data structures in Java that allow you to store multiple elements of the same type in a contiguous memory location. Understanding array type basics is crucial for effective Java programming.
Array Declaration and Initialization
In Java, arrays can be declared and initialized in several ways:
// Method 1: Declare and initialize with specific size
int[] numbers = new int[5];
// Method 2: Declare and initialize with values
String[] fruits = {"Apple", "Banana", "Cherry"};
// Method 3: Declare first, then initialize
double[] temperatures = new double[10];
temperatures[0] = 25.5;
Array Characteristics
Arrays in Java have several key characteristics:
Characteristic |
Description |
Fixed Size |
Arrays have a fixed length once created |
Type Specific |
Can only store elements of a single type |
Zero-Indexed |
First element is at index 0 |
Memory Efficiency |
Provides direct memory access |
Memory Representation
graph TD
A[Array Memory Allocation] --> B[Contiguous Memory Blocks]
B --> C[Element 0]
B --> D[Element 1]
B --> E[Element 2]
B --> F[Element n]
Common Array Operations
Accessing Elements
int[] numbers = {10, 20, 30, 40, 50};
int firstElement = numbers[0]; // 10
int thirdElement = numbers[2]; // 30
Iterating Through Arrays
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Enhanced for loop
for (int number : numbers) {
System.out.println(number);
}
Array Limitations
- Fixed size after creation
- Cannot change size dynamically
- Type safety is limited without generics
Best Practices
- Always initialize arrays before use
- Check array bounds to prevent
ArrayIndexOutOfBoundsException
- Use appropriate data structures for dynamic collections
Practical Example on Ubuntu 22.04
Here's a complete example demonstrating array usage:
public class ArrayDemo {
public static void main(String[] args) {
// Create an array of integers
int[] scores = {85, 92, 78, 90, 88};
// Calculate average
int sum = 0;
for (int score : scores) {
sum += score;
}
double average = (double) sum / scores.length;
System.out.println("Average Score: " + average);
}
}
Conclusion
Understanding array type basics provides a solid foundation for more advanced Java programming techniques. LabEx recommends practicing these concepts to build strong programming skills.