25

Why does private Boolean shouldDropTables; assign true by default to the variable instead of NULL, like when writing private Integer anInteger;?

I am asking because I came across some code where there was an evaluation on a shouldDropTables Boolean variable being NULL or not determining whether to execute a method.

kapex
  • 27,631
  • 6
  • 104
  • 117
camiloqp
  • 1,140
  • 5
  • 18
  • 34
  • 4
    "Why does private Boolean shouldDropTables; assign true by default to the variable instead of NULL" It does not. Some other code is needed for that, which is not shown in this question. โ€“ Suma Jul 03 '18 at 10:50
  • The answers here are good but there is no context and wrong assumptions. This question is not on topic for SO โ€“ EpicKip Jul 03 '18 at 11:08

6 Answers6

92

Boolean (with a uppercase 'B') is a Boolean object, which if not assigned a value, will default to null. boolean (with a lowercase 'b') is a boolean primitive, which if not assigned a value, will default to false.

Boolean objectBoolean;
boolean primitiveBoolean;

System.out.println(objectBoolean); // will print 'null'
System.out.println(primitiveBoolean); // will print 'false'
geocodezip
  • 153,563
  • 13
  • 208
  • 237
nicholas.hauschild
  • 41,623
  • 9
  • 123
  • 118
12

No.

Boolean is null by default.

TylerH
  • 20,816
  • 57
  • 73
  • 92
jmj
  • 232,312
  • 42
  • 391
  • 431
5

It's NULL by default. Because it's a Boolean Object.

Object 'Boolean' =  NULL value          // By default,
Primitive type 'boolean' = false value  // By default.
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Saurabh Gokhale
  • 51,864
  • 34
  • 134
  • 163
3

I just wanted to add one point (for beginners) regarding a primitive boolean variable.

As @99tm answered, the default value is "false". This is correct for instance or class variables.

If you have a method local variable (i.e. local to a method) as a primitive boolean, there is no default value and it is not an Object so it also cannot be null.

You must initialize it before using it, otherwise it's a compilation error.

Adam
  • 4,955
  • 4
  • 47
  • 85
sakura
  • 2,239
  • 2
  • 23
  • 38
  • I never knew that about primitives. Now I'll have to look up what `int` and `double` are initialized to when instance variables. โ€“ Adam Nov 29 '18 at 11:25
3

Perhaps you're not seeing some initialization.

It has null by default. See this sample:

$ cat B.java
class B {
        private Boolean shouldDrop;
        public static void main( String ... args ) {
                System.out.println( new B().shouldDrop );
        }
}

$ javac B.java

$ java B
null

I hope that helps

OscarRyz
  • 190,799
  • 110
  • 376
  • 555
2

JLS 9, 4.12.5. Initial Values of Variables

  • For type boolean, the default value is false.

  • For all reference types (ยง4.3), the default value is null.

Boolean is a reference type, therefore the default value is null.

Roland
  • 7,028
  • 12
  • 58
  • 109