Saturday, February 4, 2012

Java 7 - Binary Literals

Java 7 enables developers to 'create' and assign binary values to integral types (byte, short, int, and long) . Binary values starts with 0b or 0B followed by and combination of 0s and 1s. For instance

0b1111 is equivalent to 15.

You can perform arithmetic operations as well as comparisons. Below is the code which demonstrates the use of binary literals

package com.benjmaz.literals;
/***
 * 
 * @author Ben Mazyopa
 * The purpose of this code is to illustrate the use of binary strings
 */
public class BinaryLiterals {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //assigns 15 to x
  int a=0b1111;
  //assigns a values decimal
  int b=15;
  long c=a;
  float d=-0b100111;
  
  // A 64-bit 'long' value. Note the "L" suffix:
  double e= 0b1010000101000101101000010100010110100001010001011010000101000101L;
  // A 64-bit 'long' value. Note the "L" suffix:
  long f = 0b1010000101000101101000010100010110100001010001011010000101000101L;
  
  //adds 15 + 15 and stores to ans
  int ans =a+b;
  //prints 30 = 15 + 15
  System.out.format("%d = %d + %d%n",ans,a,b);
  //prints true = 15 == 15
  System.out.format("%s = %d == %d%n",c==a,c,a);
  //prints d = -39.0
  System.out.println("d = " + d );
  System.out.println("e = " + e );
  System.out.println("f = " + f );
 }
}

The above code will output the following

30 = 15 + 15
true = 15 == 15
d = -39.0
e = -6.8258723397796086E18
f = -6825872339779608251

For more information consult oracle technotes

No comments:

Post a Comment