Java 7: Binary literals

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

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.


        Suggested Articles




Sar Maroof is graduated from HBO Amsterdam "higher professional education". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer for several big as well as small companies and later as a freelancer. He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

 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 *

Sarmaroof © 2017