How do I define an integer constant in binary format?

The JDK 7 add a small feature to work with a binary number. In the previous JDK we have to use the Integer.parseInt() method if we need to work with other base number. But with this new feature introduced in the Project Coin we can simplify the code when we work with the binary number.

To specify a binary literal in the code, add the prefix 0b or 0B to the number. The following code snippet show you how to write the binary literals:

package org.kodejava.example.fundamental;

public class BinaryLiteralExample {
    public static void main(String[] args) {
        // In JDK 6 and the previous version you must use the
        // Integer.parseInt() method to define a number using
        // a binary literal.
        int x = Integer.parseInt("00101010", 2);
        System.out.println("x = " + x);

        // In the new JDK 7 you can simply use the following
        // binary literal to define a number using a binary
        // literal.
        int y = 0b00101010;
        System.out.println("y = " + y);
    }
}

The result of our code snippet:

x = 42
y = 42

How do I convert decimal to binary?

In this example you will learn how to convert decimal number to binary number. To convert decimal number to binary we can use Integer.toBinaryString() method. This method takes a single parameter of integer and return a string that represent the equal binary number.

If you want to convert the other way around, from binary string to decimal, you can use the Integer.parseInt() method. This method takes two parameters. First, the string that represents a binary number to be parsed. The second parameter is the radix to be used while parsing, in case for binary number the radix is 2.

package org.kodejava.example.lang;

public class IntegerToBinaryExample {
    public static void main(String[] args) {
        int integer = 127;
        String binary = Integer.toBinaryString(integer);
        System.out.println("Binary value of " + integer + " is "
                + binary + ".");

        int original = Integer.parseInt(binary, 2);
        System.out.println("Integer value of binary '" + binary
                + "' is " + original + ".");
    }
}

Here is the result of our program.

Binary value of 127 is 1111111.
Integer value of binary '1111111' is 127.