Why Boolean.java Choose `1231` for TRUE and `1237` for FALSE

Published on — Dec. 05, 2022
#java

If you have ever read the source code of Boolean.java, you may notice two magic numbers in hashCode(boolean) method. Why these two numbers?


The author of Effective Java used the Boolean valueOf(boolean) method as an example of the static factory, which is a way to encapsulate the instantiation from users for a variety of reasons. As a result, I began reading the source code of the Boolean class in search of new ideas.

If you’ve ever read it, you may have noticed two magic numbers in the method hashCode(boolean), as I did:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  /**
   * Returns a hash code for a {@code boolean} value; compatible with
   * {@code Boolean.hashCode()}.
   *
   * @param value the value to hash
   * @return a hash code value for a {@code boolean} value.
   * @since 1.8
   */
  public static int hashCode(boolean value) {  // blogger's comment: line 243
    return value ? 1231 : 1237;
  }

1231 and 1237.

To be honest, I didn’t notice if either of these two numbers has any special meanings or cultural background. However, because these two numbers are used as hash values, I can confidently treat them as prime numbers.

The primary reason for using prime numbers as hash values is to reduce collisions.

Therefore, we must select two prime numbers to represent these two distinct values. Not too large, as this will reduce efficiency, and not too small, as this will increase conflict.

As a result, 1231 and 1237 are two sufficiently large enough prime numbers. So, what now? There are 1,167 prime numbers between 1,000 and 10,000, which means we have so many choices.

To keep myself from pondering this meaningless question for too long, I kept searching online for an interesting enough answer, such as this one.

In addition to all that’s said above it can also be a small easter egg from developers:

true: 1231 => 1 + 2 + 3 + 1 = 7

7 - is a lucky number in European traditions;

false: 1237 => 1 + 2 + 3 + 7 = 13

13 (aka Devil’s dozen) - unlucky number.

original post: stack overflow

Perhaps those two numbers are an easter egg, or simply two sufficiently large random prime numbers. We may never know what happened because they did not leave a message in the comment. But it did kill a lot of my time, including this short article.