1

I have a boolean which checks if an action is to be performed or not, the boolean is being being accessed through setters and getters, I have other booleans am accessing in a similar way and they are not giving me any errors except this one, at first I was checking it in a piece of code within a seperate thread and that part was not working without producing an exception so I put it in a toggleButton just to do a simple read and write on it, then the nullPointerException came up, here is my code I have commented it

toggleButton.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override public void handle(MouseEvent event) {
         //this part is executing perfectly
         //meaning my toggleButton is ok
         System.out.println("Toggle Button Clicked");

         //this is where I am getting the NullPointerException
         if(!getblackAndWhite()){

            setblackAndWhite(true);

         }else{

              setblackAndWhite(false);

          }
        }});


private void setblackAndWhite(Boolean blackAndWhite)

{
    this.blackAndWhite = blackAndWhite;
}

private Boolean getblackAndWhite()
{
    return this.blackAndWhite;
}
Wendie Lamero
  • 59
  • 1
  • 12

3 Answers3

3

Then blackAndWhite is null (the default value). Initialize it when you declare it (assuming you want to start with false) that might look something like,

private Boolean blackAndWhite = false;

or in getblackAndWhite() check for null. Like,

public Boolean getblackAndWhite() {
    if (blackAndWhite == null) return false;
    return blackAndWhite;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • :D you dont say :D I guess I skipped that part of the book that says a boolean should be initialized, i thought it was a simple data type – Wendie Lamero Jan 21 '16 at 00:05
  • 2
    Or change to use a primitive boolean type and not the wrapper type. The primitive has a default value of false to start with, so if you forget to initialize it defaults to false and you can avoid the NPE. – Kevin Hooke Jan 21 '16 at 00:07
  • @WendieLamero `boolean` is a primitive type, it's default value (as an instance variable) is `false`. `Boolean` is a reference type, it's default value (as an instance variable) is `null`. – James_D Jan 21 '16 at 00:12
2

If you are not setting the value of blackAndWhite in your constructor and you call getblackAndWhite() before it is set you will get a null pointer exception (NPE)

Ben Glasser
  • 3,216
  • 3
  • 24
  • 41
1

Boolean is an object. Is it initialised?