How to initialize array elements in Java

11 Answers

0 votes
// 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

*/

 



answered 5 days ago by avibootz
edited 5 days ago by avibootz
0 votes
// Create First, Then Assign Elements Individually

/**
 * Title:
 * Assigning Array Elements Individually
 *
 * Description:
 * Elements are initialized one at a time.
 */

public class IndividualAssignment {

    public static void main(String[] args) {

        int[] scores = new int[5];

        scores[0] = 90;
        scores[1] = 85;
        scores[2] = 95;
        scores[3] = 88;
        scores[4] = 92;

        for (int i = 0; i < scores.length; i++) {
            System.out.printf("scores[%d] = %d%n", i, scores[i]);
        }
    }
}


/*
run:

scores[0] = 90
scores[1] = 85
scores[2] = 95
scores[3] = 88
scores[4] = 92

*/

 



answered 5 days ago by avibootz
0 votes
// Initialize Using a Loop

/**
 * Title:
 * Initializing an Array with a Loop
 *
 * Description:
 * Array values are calculated dynamically.
 */

public class LoopInitialization {

    public static void main(String[] args) {

        int[] squares = new int[10];

        // Fill the array with square numbers.
        for (int i = 0; i < squares.length; i++) {
            squares[i] = (i + 1) * (i + 1);
        }

        System.out.println("Square numbers:");

        for (int value : squares) {
            System.out.println(value);
        }
    }
}


/*
run:

Square numbers:
1
4
9
16
25
36
49
64
81
100

*/

 



answered 5 days ago by avibootz
0 votes
// Fill Entire Array with the Same Value

/**
 * Title:
 * Filling an Entire Array with the Same Value
 *
 * Description:
 * Arrays.fill() sets every element to the same value.
 */

import java.util.Arrays;

public class FillArray {

    public static void main(String[] args) {

        int[] data = new int[10];

        // Assign 100 to every element.
        Arrays.fill(data, 100);

        System.out.println(Arrays.toString(data));
    }
}


/*
run:

[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

*/

 



answered 5 days ago by avibootz
0 votes
// Initialize from a Factory Method

/**
 * Title:
 * Initializing Arrays Using a Factory Method
 *
 * Description:
 * Encapsulates array creation logic in a separate method.
 */

import java.util.Arrays;

public class FactoryMethodInitialization {

    private static int[] createSequence(int size) {

        int[] result = new int[size];

        for (int i = 0; i < result.length; i++) {
            result[i] = i + 1;
        }

        return result;
    }

    public static void main(String[] args) {

        int[] numbers = createSequence(10);

        System.out.println(Arrays.toString(numbers));
    }
}


/*
run:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

*/

 



answered 5 days ago by avibootz
0 votes
// Using Streams (Modern Java)

/**
 * Title:
 * Stream-Based Array Initialization
 *
 * Description:
 * Uses IntStream to create and initialize arrays.
 */

import java.util.Arrays;
import java.util.stream.IntStream;

public class StreamInitialization {

    public static void main(String[] args) {

        int[] numbers = IntStream.rangeClosed(1, 10)
                                 .toArray();

        System.out.println(Arrays.toString(numbers));
    }
}


/*
run:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

*/

 



answered 5 days ago by avibootz
0 votes
// Stream Initialization with Computed Values

/**
 * Title:
 * Computed Array Initialization Using Streams
 *
 * Description:
 * Generates square numbers using Stream operations.
 */

import java.util.Arrays;
import java.util.stream.IntStream;

public class ComputedStreamInitialization {

    public static void main(String[] args) {

        int[] squares =
                IntStream.rangeClosed(1, 10)
                         .map(n -> n * n)
                         .toArray();

        System.out.println(Arrays.toString(squares));
    }
}


/*
run:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

*/

 



answered 5 days ago by avibootz
0 votes
// Default Initialization

/**
 * Title:
 * Default Array Initialization
 *
 * Description:
 * Java automatically assigns default values.
 */
public class DefaultInitialization {

    public static void main(String[] args) {

        int[] integers = new int[5];
        boolean[] flags = new boolean[5];
        String[] names = new String[5];

        System.out.println("Default int values:");
        for (int value : integers) {
            System.out.println(value);
        }

        System.out.println();

        System.out.println("Default boolean values:");
        for (boolean flag : flags) {
            System.out.println(flag);
        }

        System.out.println();

        System.out.println("Default String values:");
        for (String name : names) {
            System.out.println(name);
        }
    }
}


/*
run:

Default int values:
0
0
0
0
0

Default boolean values:
false
false
false
false
false

Default String values:
null
null
null
null
null

*/

 



answered 5 days ago by avibootz
0 votes
// Multidimensional Array Initialization

/**
 * Title:
 * Initializing a Two-Dimensional Array
 *
 * Descriptcon:
 * Demonstrates matrix initialization.
 */

public class TwoDimensionalInitialization {

    public static void main(String[] args) {

        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        for (int[] row : matrix) {

            for (int value : row) {
                System.out.printf("%4d", value);
            }

            System.out.println();
        }
    }
}


/*
run:

   1   2   3
   4   5   6
   7   8   9

*/

 



answered 5 days ago by avibootz
0 votes
// Jagged (Ragged) Array Initialization

/**
 * Title:
 * Initializing a Jagged Array
 *
 * Description:
 * Each row can have a different size.
 */

public class JaggedArrayInitialization {

    public static void main(String[] args) {

        int[][] data = {
                {1},
                {2, 3},
                {4, 5, 6},
                {7, 8, 9, 10}
        };

        for (int row = 0; row < data.length; row++) {

            System.out.print("Row " + row + ": ");

            for (int value : data[row]) {
                System.out.print(value + " ");
            }

            System.out.println();
        }
    }
}


/*
run:

Row 0: 1 
Row 1: 2 3 
Row 2: 4 5 6 
Row 3: 7 8 9 10 

*/

 



answered 5 days ago by avibootz
0 votes
// Initialize Object Arrays

/**
 * Title:
 * Initializing an Object Array
 *
 * Description:
 * Arrays can store references to objects.
 */

public class ObjectArrayInitialization {

    public static void main(String[] args) {

        String[] languages = {
                "Java",
                "Kotlin",
                "Scala",
                "Groovy"
        };

        for (String language : languages) {
            System.out.println(language);
        }
    }
}


/*
run:

Java
Kotlin
Scala
Groovy

*/

 



answered 5 days ago by avibootz
...