Java's C/C++ heritage lets you express integer literals in decimal (63), hexadecimal (0x3f), and octal (077) notation. JDK 7 also allows you to express integer literals in binary notation by prefixing a sequence of ones and/or zeroes with 0b or 0B:
int x = 0b10101111; System.out.printf ("%d%n", x); // Output: 175
Perhaps you're wondering why binary literals were chosen for inclusion in JDK 7. Derek Foster, the originator of this feature, provides the rationale in his Project Coin proposal, Binary literals (Version 2). (Launched in early 2009, Project Coin was a Sun Microsystems sponsored project that solicited requests from the developer community for language enhancements.)
According to Foster, "Code using bitwise operations is more readable and easier to verify against technical specifications that use binary numbers to specify constants." Also, Foster mentions that having to mentally translate from binary to hexadecimal can lead to errors.
Of course, you could always rely on Integer's parseInt() method to convert a string of binary digits to an integer. For example: Integer.parseInt ("00110011", 2) returns 51. However, this method call is problematic for the following reasons:
- The method call is more verbose than just specifying the literal. The method call syntax clutters the code.
- The method call exacts a performance penalty[md]specifying a constant results in faster execution.
- The compiler cannot inline a method call's return value, but can inline a constant's value.
- The method call results in a thrown exception when an error is detected in the string. Let's catch the error at compile time.
- Unlike a binary literal, you cannot express a method call as a switch statement's selector value. For example, case Integer.parseInt ("00001110", 2): is syntactically incorrect (and ugly), whereas case 0B00001110: is syntactically correct (and easier to read).