Saturday, July 30, 2011

Java 7: Underscores in Numbers and Binary Literals

In order to aid readability, you can now place underscores between numbers but you must start and end with a digit. For example:
int million = 1_000_000;
float pi = 3.14_159f;
JDK7 also allows you to express integer literals in binary form. This makes it easier to read code which uses bitwise operations. In order to do this, prefix your binary sequence with 0b or 0B. For example:
//previously, you would have had to do it like this:
int x = Integer.parseInt("1000", 2);

//in jdk7, you can create a binary literal like this:
int eight = 0b1000;

//easier to read bitwise operations
int four = 0b1000>>1;
Further Reading:
Underscores in Numeric Literals Binary Literals

1 comment:

  1. Thanks for your wonderful information which helped us to join java online training