- Author

- Name
- Nelson Silva
- Social
Introduction
Arrays are a fundamental part of programming in Java. They allow storing multiple values of the same type in a single variable, making it easier and more efficient to manipulate data sets.
What is an Array?
An array is a data structure that stores elements of the same type sequentially. In Java:
- Each element of an array has an index, which starts at 0 and goes up to "n-1", where "n" is the size of the array.
- Arrays have a fixed size, which means that once created, it is not possible to change their size.
- The data type stored in an array can be any primitive type, object, or another array (multidimensional arrays).
Declaration and Initialisation
There are several ways to declare and initialise arrays in Java:
- Declare, then initialise:
int[] numbers = new int[5];
- Declare and initialise simultaneously:
int[] numbers = {1, 2, 3, 4, 5};
- Declare using the object type (generally used for object arrays):
String[] names = new String[]{"John", "Anna", "Carlos"};
Accessing Array Elements
To access an element in an array, use the index of the desired element:
int firstNumber = numbers[0]; // Accesses the first element
Practical Example
package com.caffeinealgorithm.programaremjava;
public class Arrays {
public void Run() {
String[] colors = new String[] {
"Blue", "Green", "Yellow", "Red", "Orange"
};
System.out.printf("Number of colors: %d\n", colors.length);
System.out.printf("First color: %s\n", colors[0]);
System.out.printf("Last color: %s", colors[colors.length - 1]);
}
}
Conclusion
Arrays are a powerful and essential tool for any Java programmer. They allow efficient manipulation of data sets and are widely used in many algorithms and real-world applications.