Java Program to Illustrate Use of Binary Literals
A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value. So, we can express binary digits in a program by assigning them to variables, and the output of those variables after executing the program will be decimal digits.
Implementing Binary literals in Java:
We can explore the ways in which we can implement and use binary literals in Java programming language. The first and following Java program is an example to implement different types of binary literals. As mentioned above Java allows us to express byte, short, int, and long types of binary literals.
Java
public class GFG {
public static void main(String[] args)
{
byte a1 = 0b011;
byte a2 = 0B101;
System.out.println( "Binary Literal in Byte----->" );
System.out.println( "a1 = " + a1 + ", "
+ "a2 = " + a2);
short b1 = 0b101;
short b2 = 0B111;
System.out.println( "Binary Literal in Short----->" );
System.out.println( "b1 = " + b1 + ", "
+ "b2 = " + b2);
int c1 = 0b011;
int c2 = 0B111;
System.out.println(
"Binary Literal in Integer----->" );
System.out.println( "c1 = " + c1 + ", "
+ "c2 = " + c2);
long d1 = 0b0000011111100011;
long d2 = 0B0000011111100001;
System.out.println( "Binary Literal in Long----->" );
System.out.println( "d1 = " + d1 + ", "
+ "d2 = " + d2);
}
}
|
Output
Binary Literal in Byte----->
a1 = 3, a2 = 5
Binary Literal in Short----->
b1 = 5, b2 = 7
Binary Literal in Integer----->
c1 = 3, c2 = 7
Binary Literal in Long----->
d1 = 2019, d2 = 2017
In Java, operators can be used on binary literals to perform operations. The following Java program is an example to implement different mathematical and comparison operations on binary literals. The results of these operations on binary literals are decimal digits.
Java
public class GFG {
public static void main(String[] args)
{
byte n1 = 3 ;
byte n2 = 0b011;
byte n3 = -0b111;
byte n4 = 0b1101;
System.out.println( "n1 = " + n1);
System.out.println( "n2 = " + n2);
System.out.println( "n3 = " + n3);
System.out.println( "n4 = " + n4);
System.out.println( "is n1 and n2 equal: "
+ (n1 == n2));
System.out.println( "n2 + 1 = " + (n2 + 1 ));
System.out.println( "n3 + 1 = " + (n3 + 1 ));
System.out.println( "n4 x 2 = " + (n4 * 2 ));
}
}
|
Output
n1 = 3
n2 = 3
n3 = -7
n4 = 13
is n1 and n2 equal: true
n2 + 1 = 4
n3 + 1 = -6
n4 x 2 = 26
Last Updated :
09 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...