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
  • 28,903
  • 6
  • 107
  • 121
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
  • 158,664
  • 13
  • 220
  • 245
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
12

No.

Boolean is null by default.

TylerH
  • 20,799
  • 66
  • 75
  • 101
jmj
  • 237,923
  • 42
  • 401
  • 438
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,738
  • 21
  • 105
  • 131
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
4

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
  • 5,215
  • 5
  • 51
  • 90
sakura
  • 2,249
  • 2
  • 26
  • 39
  • 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
  • 196,001
  • 113
  • 385
  • 569
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,525
  • 13
  • 61
  • 124