Binary literals is one of the new feature added in Java 7. We already know that we can represent integrals types (byte, short, int, long) in Binary and Hexadecimal formats. From Java 7, we can represent them in binary format also.

Binary Literals

To represent an integral number in binary format, that binary number has to be prefixed with 0b or 0B. So from Java 7 we can represent a number in 3 different formats as Binary, Hex and Base10.

Example:

BinaryLiterals.java

[sourcecode language=”java”]

public class BinaryLiterals {
    public static void main(String args[]) {
        byte ten = 10; // Representing 10 in base10 format
        byte tenBinary = 0b1010; // Representing 10 in binary format
        System.out.println("Normal Format : " + ten);
        System.out.println("Binary Format : " + tenBinary);
        // Checks whether the value is same or not
        System.out.println("is Dec == to binary : " + (ten == tenBinary));

        // We can use _ in binary literals,
        byte seven = 0b000_0111;
        // having underscore in binary literals
        System.out.println("Binary Literal with Underscores : " + seven);
    }
}
[/sourcecode]

[box type=”success” align=”alignleft” class=”” width=”100%”]

Output :

Normal Format : 10
Binary Format : 10
is Dec == to binary : true
Binary Literal with Underscores : 7

[/box]

Points to note:

  1. To represent negative numbers don’t make binary literals starting 0 in 0B as 1. You can use normal way of representing like -0B01100
  2. Since a byte primitive type can hold a maximum of 8 bits, giving more than 8 bits, like byte num = 0B1100011111 will result in compiler error Type mismatch: cannot convert from int to byte.  This same error is applicable for other integral numbers as well.
  3. We can also use the  Underscores in Numeric Literals concept in Binary Literals.

Happy Learning 🙂