So, with the release of Java SE 7, binary notation comes standard out of the box. The syntax is pretty straight forward and obvious, if you have a decent understanding of binary:
byte fourTimesThree = 0b1100; byte data = 0b0000110011; short number = 0b111111111111111; int overflow = 0b10101010101010101010101010101011; long bow = 0b101010101010101010101010101010111L;
And, in particular, when declaring class level variables as binary files, there is no problem when initializing a static variable using binary notation:
public static final int thingy = 0b0101;
Just be careful not to overflow numbers with too much data, otherwise you will get a compiler error:
byte data = 0b1100110011;
Now, if you really want to get some fantasy, you can combine this other neat new feature in Java 7, known as numeric literals with underscores. Take a look at these fancy binary notation examples with literal underscores:
int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011; long bow = 0b1__01010101__01010101__01010101__01010111L;
Now is it not so beautiful and clean, not to mention well readable?
I pulled these code snippets from a short article that I wrote about a topic on TheServerSide. Feel free to check it out for more details:
Java 7 and Binary Notation: Mastering the OMP Java Programmer Exam (OCPJP)
Cameron McKenzie Dec 20 2018-11-12T00: 00Z
source share