Skip to content

Instantly share code, notes, and snippets.

@geluso
Created August 29, 2018 17:44
Show Gist options
  • Save geluso/3dd46c45fa5d2968f26fd8aad3589644 to your computer and use it in GitHub Desktop.
Save geluso/3dd46c45fa5d2968f26fd8aad3589644 to your computer and use it in GitHub Desktop.

Upper-case Boolean

In your ProfileController you have a strange type for booleans. You should prefer to use lower-case boolean when you make a single boolean variable. You should only use upper-case Boolean when you’re identifying the type of something in a generic class between diamonds <Boolean>.

Boolean found = false;
Boolean endFound = false;

The lower-case boolean is a primitive value in Java. The upper-case version is called a “boxed” class. Basically the upper-case boxed version is a class that simply wraps the primitive value. Primitive values don’t work as generic types between diamonds because only classes are allowed between diamonds, not primitives.

All boxing does is wrap around the primitive value. A box class might look like this:

class Boolean {
  private boolean value;

  public Boolean(boolean value) {
    this.value = value;
  }

  public boolean get() {
    return this.value;
  }

  public boolean set(boolean value) {
    this.value = value;
  }
}

Yes, it’s ridiculous, but that’s just what needs to happen. Java requires that the primitive value be wrapped in a class in order to include it in the overall class hierarchy.

The primitive type boolean does not exist as an Object or in the class hierarchy. The boxed class Boolean contains the primitive value and exists in the class hierarchy. It is a sub-class of Object, like all other classes. The Boolean class also implements the Serializable, and Comparable<Boolean> interfaces and has methods attached to it like .hashCode(), .equals(), and .toString().

Remember: primitive values do not have methods attached to them. Wrapping primitive boolean values in the Boolean class allows us to have methods attached and makes them entirely more useful.

Again. use boolean when you’re storing one boolean value as a variable. Use the Boolean class to wrap, or “box,” boolean values when you’re using them as an identifier like when specifying a generic class.

Read about boxing and unboxing:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment