Binary Literals in Java – Java 7 Feature

Filed Under: Java

Binary literals are new features in Java 7. As you all know that we can write integral types (byte, short, int, and long) in Binary and Hexadecimal formats. However, from Java 7 onwards we can write these numbers in binary format also. The number should be prefixed with 0b or 0B to be treated as binary literal.

Binary Literals in Java

This feature is very helpful to bit-oriented systems like processors, network protocols and bitmapped hardware device. Earlier the programmers used to transform from binary to decimal/hexadecimal and vice versa. Using this feature will remove this transformation and chances of error will be less in this conversion.

Also, the code using bitwise operations will be more readable with this feature.

Let’s see binary literals in action with a simple java program:


package com.journaldev.util;

public class Java7Literals {

	public static void main(String[] args) {
		int i=0b0111;
		byte b=(byte) 0b0111;
		long l=(long) 0B0111L;
		System.out.println("i="+i);
		System.out.println("b="+b);
		System.out.println("l="+l);
	}

}

Output of the above program is:


i=7
b=7
l=7
x=7

Comments

  1. phani says:

    how is x printed. there is no seperate println for it? pls explain

  2. Ali says:

    Correction:

    “As you all know that we can write integral types (byte, short, int, and long) in Binary and Hexadecimal formats but from Java 7 onwards we can write these numbers in binary format also. ”

    It mentions Binary and Hexadecimal, but it should be Octal and Hexadecimal formats.

    1. alok says:

      yes this should be corrected as “octal” instead of binary.

  3. manikandan says:

    For the Above Prg “x” is not initialized…..

    1. alok says:

      yes ,””x” is not initialized despite we can see it in output.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages