Saturday, August 13, 2022

Binary Numbers in Java

Binary Literals are the literals that consist of only 0s and 1s. Java allows you to declare a binary number by adding a prefix `0b` or `0B`.


Example 1

public class BinaryNumber {
    public static void main(String[] args)
    {
        byte decNumber = 3; // Decimal number
        byte binNumber = 0b011; // Binary value of 3
        byte binNumber1 = 0B011; // Binary value of 3
  
        System.out.println("Decimal Number is " + decNumber);
        System.out.println("Binary Number with b is " + binNumber);
        System.out.println("Binary Number with B is " + binNumber);
    }
}

Output
Decimal Number is 3
Binary Number with b is 3
Binary Number with B is 3

Let's take another example.

Example 2

public class BinaryNumber {
    public static void main(String[] args)
    {
        byte decNumber = 3; // Decimal number
        byte binNumber = 0b101; // Binary value of 5
        byte binNumber1 = 0B101; // Binary value of 5
  
        System.out.println("Decimal Number is " + decNumber);
        System.out.println("Binary Number with b is " + binNumber);
        System.out.println("Binary Number with B is " + binNumber);
    }
}

Output

Decimal Number is 3
Binary Number with b is 5
Binary Number with B is 5

No comments:

Post a Comment

Setting up the environment variables for Java in Windows

How to set the Environment Variables for Java in Windows? Step 1 -   Go to Control Panel -> System and Security  System .  In System, sel...