You are creating an array of Boolean, not boolean, and you are trying to use it before filling it with Boolean objects, so it should be no surprise that this will throw a NPE.
Solutions:
- Create an array of boolean and if initialized, it will be filled with default false values.
- Create an array of Boolean if you must (such as if using in a JTable model), but be sure that every item is initialized to a valid Boolean instance before using the array.
e.g., change from
Boolean[] bool = new Boolean[5];
to
boolean[] bool = new boolean[5];
or
Boolean[] bool = {Boolean.FALSE, Boolean.FALSE, Boolean.FALSE,
Boolean.FALSE, Boolean.FALSE};
Edit
Please understand that boolean is a primitive type, and if a boolean variable is not explicitly initialized, is not assigned a value, it defaults to false.
Boolean on the other hand is a reference type that "boxes" a boolean, provides a reference variable that can be used in the place of the boolean primitive where references are required, such as in collections. A Boolean variable, as is true for all reference types, defaults to a null value if not explicitly assigned to an instance.
Edit 2
Note that if you use Strings, you will run into the same problem. For example
String unAssigned;
if (unAssigned.equals("foo") {
System.out.println("the method above throws a NPE");
}
or
String[] strings = new String[5];
// all the strings items above are null
Edit 3
You wonder why this doesn't do the same thing: String s = new String();
- You're creating a new String object and assigning it to the
s variable, so s is not null.
- With the Boolean array, yes you're assigning a new array to the variable, so the array is not null, but the items held by the array are null.
- You're not using a String array anywhere, so it's no where near the same thing. Come on now, let's compare apples to apples, not apples to oranges.
- As an aside, you should almost never use
new String() as it circumvents the String pool and can lead to inefficient code with needless creation of extra String objects.