What am I doing wrong when initializing a boolean array in Java, and how can I correctly set all elements to `false`?

I’m trying to initialize a boolean array in Java like this:

public static Boolean freq[] = new Boolean[Global.iParameter[2]];
freq[Global.iParameter[2]] = false;

But I get an error. What exactly is causing the issue, and how can I properly initialize all elements of the array to Boolean.FALSE?

(I’ve been writing Java for over a decade, and initializing arrays can trip you up in sneaky ways.)

You’re actually pretty close with how you’re trying to initialize a boolean array java setup, but there are two common pitfalls you’ve hit:

:no_entry_sign: What’s going wrong?

public static Boolean freq[] = new Boolean[Global.iParameter[2]];
freq[Global.iParameter[2]] = false;

Here’s why this doesn’t work:

  • Index Out of Bounds: Arrays in Java are 0-indexed. So if your array size is n, the last valid index is n-1. Trying to access freq[n] will throw an ArrayIndexOutOfBoundsException.
  • Object vs Primitive: You’re using Boolean[] (object type) instead of boolean[] (primitive). Object arrays default to null, not false, which can cause NullPointerExceptions if accessed before being set.

:white_check_mark: Better Approach If all you need is true/false values and not nulls, use the primitive type. Java initializes all elements of a primitive boolean array java to false by default:

public static boolean[] freq = new boolean[Global.iParameter[2]];

You don’t have to manually set anything — the array is already filled with false values.

(I’ve run into this too, especially when working with object arrays for special logic like tri-state flags.)

@devan-skeem nailed the primitive side of things, but if you’re sticking with a Boolean[] for some reason — maybe because you need nulls for additional logic or optional flags — you’ll have to initialize the values yourself. Why? Because in a Boolean array java, the default values are null, not false.

Here’s a clean way to do it:

public static Boolean[] freq = new Boolean[Global.iParameter[2]];
for (int i = 0; i < freq.length; i++) {
    freq[i] = Boolean.FALSE;
}

It’s a bit more verbose, but it ensures every element is safely set to Boolean.FALSE. This helps avoid surprises when checking values later in your code.

(Been optimizing Java snippets for readability and performance — little tweaks add up over time!) Love how @prynka.chatterjee explained the manual loop! But if you’re looking for something a bit more elegant and concise — especially in a Boolean array java context — Java’s Arrays.fill() utility is your friend.

Here’s how you do it:

import java.util.Arrays;

public static Boolean[] freq = new Boolean[Global.iParameter[2]];
Arrays.fill(freq, Boolean.FALSE);

It’s cleaner, reduces boilerplate, and makes it crystal clear that you’re initializing the entire array with a consistent default value.