Java 7: Binary literals

  Java Features     Java 5     Java 7     Java 8  
Java 7 features
 Binary literals |   Strings in switch statements |   Catching multiple exceptions |   Try with resources |   Type inference |   Underscores in numeric literals |   By date 

This feature in JSE7 allows the primitive variables byte, short, int and long to express the binary number system by adding the prefix 0b or 0B to the number as shown in the following example. For more info click here to read Oracle’s explanation.

Example 1: Binary literal code

What is written to the standard output as the result of executing the following code?

public class MyClass
{
  public static void main(String[] args)
  {
    /* binary literal in byte, short, 
     * int and long the 0b can be lower 
     * or upper case
     */
    byte b = 0B01111;
    System.out.println("b1 = " + b);
    short s = 0b10011;
    System.out.println("s = " + s);
    int i = 0B0110101;
    System.out.println("i = " + i);
    long l = 0b0011100001;
    System.out.println("l = " + l);
  }
}
Author: Sar Maroof

Answer explanation

  • b = 0B01111 = 0 + 2³ + 2² + 2¹ + 2⁰ = 8 + 4 + 2 + 1 = 15.
  • s = 0b10011 = 2⁴ + 0 + 0 + 2¹ + 2⁰ = 16 + 2 + 1 = 19.
  • i = 0B0110101 = 0 + 2⁵ + 2⁴ + 0 + 2² + 0 + 2⁰ = 32 + 16 + 4 + 1 = 53.
  • l = 0b0011100001 = 0 + 0 + 2⁷ + 2⁶ + 2⁵ + 0 + 0 + 0 + 0 + 2⁰ = 128 + 64 + 32 + 1 = 225.

The correct answer is:

b1 = 15
s = 19
i = 53
l = 225



        Suggested Articles




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

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