-3

Please just my curiosity that could be used (code example see at line 38th(code edited))

Boolean bol = true;
Boolean bol1 = !bol;

my question are

  • its proper way, or is there (any) possible lack, issue why to avoid to use
  • is correct result is the same for boolean and Boolean
  • is there another data type in Java, where is possible toggle with expression, logical value
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319

3 Answers3

6

The second instruction will throw a NullPointerException if bol is null. If you're sure that the boolean is not null, then no problem.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

Yes, its ok.

Boolean can hold a third value "null", whearat boolean can only hold true or false.

If you have a function

public static void hi(boolean b) {...};

public static void main(String[] args){
    Boolean b = null;
    hi(b); // ... throws a NullPointerException at Runtime only
}

This is called autoboxing, because of the Reflection needs real classes with package.

Reflection also has

Void (realy wired in real code)
Integer
Float
Enum (sometimes)
Grim
  • 1,938
  • 10
  • 56
  • 123
  • 1
    What does reflection has to do with the existence of Boolean? Boolean predates reflection. It's needed mainly because collections only store objects, and becase you sometimes want a nullable Boolean. – JB Nizet Jul 30 '13 at 12:47
  • `boolean[]` is a collection too - no explicit need for `Boolean` here, even collections can contain a `Container` to only store the boolean. But you cant use Reflection to identify `hi` without the use of `Boolean` from `hi(int b)`. – Grim Jul 30 '13 at 12:51
  • boolean[] is an array. And Boolean is the standard container to only store the boolean. As I said, Boolean exists since the very beginning of Java, when reflection didn't exist yet. – JB Nizet Jul 30 '13 at 15:30
  • Boolean is cka wrapper. Yes Boolean exists since `JDK 1.0`, anyway you cant implement reflection without `Boolean`. Ill stroke introduced. – Grim Jul 30 '13 at 21:18
1

Yes, it's the correct way, and it will work with both boolean and Boolean.

Your "another data type" might possibly be integer used to store boolean as 0 and 1, although I don't know who would do that if we have real boolean.

There, you would use this:

int a = 1;
int negated = 1-a;
MightyPork
  • 18,270
  • 10
  • 79
  • 133