How to initialize different types of arrays to zero in Java

1 Answer

0 votes
/**
    This program demonstrates how to initialize different types of arrays
    to zero in Java. It covers:
      - Primitive numeric arrays
      - Arrays of objects with a defined "zero state"
      - Arrays of wrapper types

    Java automatically initializes numeric primitives to zero, but we still
    show explicit initialization patterns to make the logic clear and reusable.
*/

public class ArrayZeroInit {

    // A simple class with a "zero state"
    static class Point {
        int x;
        int y;

        // Constructor for convenience
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    // Initialize an int array to zero using a loop
    static void initIntArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = 0; // explicit zero assignment
        }
    }

    // Initialize an array of Points to a zero-state object
    static void initPointArray(Point[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new Point(0, 0); // zero-state object
        }
    }

    // Initialize an array of Integer wrappers to zero
    static void initIntegerArray(Integer[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = 0; // auto-boxed zero
        }
    }

    // Print int array
    static void printIntArray(int[] arr) {
        for (int v : arr) {
            System.out.print(v + " ");
        }
        System.out.println();
    }

    // Print Point array
    static void printPointArray(Point[] arr) {
        for (Point p : arr) {
            System.out.print("(" + p.x + "," + p.y + ") ");
        }
        System.out.println();
    }

    // Print Integer array
    static void printIntegerArray(Integer[] arr) {
        for (Integer v : arr) {
            System.out.print(v + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {

        // Arrays of different types
        int[] numeric = new int[5];
        Point[] points = new Point[5];
        Integer[] boxed = new Integer[5];

        // Initialize all arrays to zero
        initIntArray(numeric);
        initPointArray(points);
        initIntegerArray(boxed);

        // Print results
        printIntArray(numeric);
        printPointArray(points);
        printIntegerArray(boxed);
    }
}


/*
run:

0 0 0 0 0 
(0,0) (0,0) (0,0) (0,0) (0,0) 
0 0 0 0 0 

*/

 



answered Aug 26 by avibootz
...