initializing a boolean array in java

JavaArraysInitialization

Java Problem Overview


I have this code

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

could someone tell me what exactly i'm doing wrong here and how would i correct it? I just need to initialize all the array elements to Boolean false. thank you

Java Solutions


Solution 1 - Java

> I just need to initialize all the array elements to Boolean false.

Either use boolean[] instead so that all values defaults to false:

boolean[] array = new boolean[size];

Or use Arrays#fill() to fill the entire array with Boolean.FALSE:

Boolean[] array = new Boolean[size];
Arrays.fill(array, Boolean.FALSE);

Also note that the array index is zero based. The freq[Global.iParameter[2]] = false; line as you've there would cause ArrayIndexOutOfBoundsException. To learn more about arrays in Java, consult this basic Oracle tutorial.

Solution 2 - Java

The array will be initialized to false when you allocate it.

All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialised to 0, arrays of booleans are initialised to false and arrays of reference types are initialised to null.

Solution 3 - Java

Arrays in Java start indexing at 0. So in your example you are referring to an element that is outside the array by one.

It should probably be something like freq[Global.iParameter[2]-1]=false;

You would need to loop through the array to initialize all of it, this line only initializes the last element.

Actually, I'm pretty sure that false is default for booleans in Java, so you might not need to initialize at all.

Best Regards

Solution 4 - Java

They will be initialized to false by default. In Java arrays are created on heap and every element of the array is given a default value depending on its type. For boolean data type the default value is false.

Solution 5 - Java

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

Global.iParameter[2]:

It should be const value

Solution 6 - Java

The main difference is that Boolean is an object and boolean is an primitive.

  • Object default value is null;
  • boolean default value is false;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionleba-levView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaJørgen FoghView Answer on Stackoverflow
Solution 3 - JavaBig EndianView Answer on Stackoverflow
Solution 4 - JavacodaddictView Answer on Stackoverflow
Solution 5 - JavaoneatView Answer on Stackoverflow
Solution 6 - JavaJavaView Answer on Stackoverflow