// Best Practices
/**
* Recommended Approaches
*
* 1. Use array literals when values are known:
*
* int[] numbers = {1, 2, 3, 4, 5};
*
* 2. Use Arrays.fill() when all elements
* should contain the same value.
*
* Arrays.fill(array, 100);
*
* 3. Use loops for calculated values.
*
* for (int i = 0; i < array.length; i++) {
* array[i] = i * i;
* }
*
* 4. Use Streams when a functional style
* improves readability.
*
* IntStream.rangeClosed(1, 10).toArray();
*
* 5. Use enhanced for-loops when you only
* need the element value.
*
* 6. Prefer array.length rather than hardcoded
* bounds.
*
* 7. Make arrays final when the reference
* should not change:
*
* final int[] numbers = {1, 2, 3};
*
* 8. Consider List<E> instead of arrays when
* the collection size must change dynamically.
*/
// Initialize During Declaration (Most Common)
/**
* Title:
* Initializing an Array During Declaration
*
* Description:
* The array is created and populated in a single statement.
*/
public class ArrayDeclarationInitialization {
public static void main(String[] args) {
// Create and initialize the array.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Array contents:");
// Use the enhanced for-loop when the index is not needed.
for (int value : numbers) {
System.out.println(value);
}
}
}
/*
run:
Array contents:
10
20
30
40
50
*/