Wednesday , January 18 2017
Home / java / Binary Literals Java 7 Example Tutorials

Binary Literals Java 7 Example Tutorials

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


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);
    }
}

Output :

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

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 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Catching Multiple Exceptions in Java 7

Catching Multiple Exceptions in Java 7 is a very good change Oracle had made in …

Leave a Reply

Your email address will not be published. Required fields are marked *