2

so i have this method:

class A(){

private Boolean Flag;

public java.lang.Boolean getFlag()
    {
        return this.Flag;
    }

public java.lang.Boolean setFlag(Boolean Flag)
    {
        this.Flag = Flag ;
    }
}

classB(){

boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag(navalFlag?"Y":"N";

}

database returns null and Flag is set to null.

What is a foolproof way where I can 100% avoid NPEs? I know Boolean to boolean casting is not a guarantee as seen from here

Update: stepping through the code, the NPE is thrown in fancyObj.getFlag()...which doesn't make sense to me. i would expect the NPE thrown in .setNavalFlag....

Community
  • 1
  • 1
bouncingHippo
  • 5,940
  • 21
  • 67
  • 107

4 Answers4

2

What is a foolproof way where I can 100% avoid NPEs?

One foolproof way is to explicitly check for null and to not attempt to unbox the Boolean unless you know it's not null.

To take your current code as an example:

boolean navalFlag = fancyObj.getFlag()

This tries to unbox the Boolean. If it's null, you get an NPE.

The following modification will not have this problem:

Boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag((navalFlag != null && navalFlag) ? "Y" : "N");
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0
Boolean navalFlag = fancyObj.getFlag()
form.setNavalFlag((navalflag != null && navalFlag) ? "Y" : "N");

Edit of the Edit, as I had understood wrongly your comment :

See my answer to the comment: boolean navalFlag = fancyObj.getFlag() is automatically translated to boolean navalFlag = fancyObj.getFlag().booleanValue()

Steph
  • 1,989
  • 14
  • 18
  • the NPE is thrown in `fancyObj.getFlag()`...which doesn't make sense to me – bouncingHippo Mar 15 '13 at 19:22
  • The problem is that `boolean navalFlag = fancyObj.getFlag()` really means `boolean navalFlag = fancyObj.getFlag().booleanValue()` (automatic conversion process named unboxing) – Steph Mar 15 '13 at 19:30
0

Change your method

public java.lang.Boolean getFlag()
{
    return this.Flag;
}

to something like

public java.lang.Boolean getFlag()
{
    (Flag==null) ? Boolean.FALSE : Flag;
}
vhunsicker
  • 538
  • 6
  • 20
0

Use boolean primitive type, not wrapper in your value object.

If you retrieve the value from database yourself, you will have to be careful, you will have to understand how to interpret null, normally it is false.

Alex Kreutznaer
  • 1,170
  • 8
  • 18