1

Im using the below code to check if a initialized boolean variable is set to True or False. When I try to run this code I get a NullPointerException error.

Can someone explain what would be the problem?

public class Scratch {
    Boolean[] bool = new Boolean[5];
    String s = new String();


    public static void main(String[] args) {
        new Scratch().mymethod();

    }

    public void mymethod() {
        if (s == "Tom"){
        System.out.println("Tom");
    }
    System.out.println("S value = "+ s);    

        if (bool[1] == true) {
            System.out.println("True");
        } else {
            System.out.println("false");
        }
    }

}
1
  • @Teo: Thanks for your responses as well.. Commented Feb 16, 2014 at 20:34

2 Answers 2

9

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.
Sign up to request clarification or add additional context in comments.

8 Comments

Perhaps add something about primitives vs boxed primitives, they can be quite confusing to beginners.
Im confused, that Im trying to use it before filling it..Doesn't it get initialized to nulls automatically?
@user1050619: yes it initializes to null, and that's your problem. Please see edit to answer.
@user1050619 They're initialized to nulls so you get a NullPointerException...
Ok, but when I declare a String which is again initialized to nulls, I dont have any problem using it..can you pls explain?
|
2

This "problem" because of Boxing about primitive in Java..

Boolean is different that boolean, like Integer and int for example...

Boolean is an object (wrap class), so it has true, false value, but it has NULL value too. While the boolean is a primitive variable, so it has only the "real" boolean value: true, and false

Linke explained in guide: The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

So Boolean b, has 3 value: true, false and null.

boolean b, has 2 value: true and false

The null value may be assigned to any variable, except variables of primitive types. And the Boolean variable "initialized" to null value, because you not call the constructor of Boolean class yet...

So if you do: String s = "HELLO", you can use it, because with tis piece of code, you automatic call the constructor of String. But if you do: String s; its value is null. The samt thing to Boolean wrapper class.

To clarify you can read this: Creating Objects

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.