hexadecimal to binary in java

Let’s learn hexadecimal to binary in java.

hexadecimal to binary in java

To convert java hex to binary first get input from user using nextLine() method of Scanner class. Meanwhile parse user input using Integer.parseInt(String s, int radix) method and store this value in integer variable ‘number’.

Integer.parseInt(String s, int radix) method parses the string argument as a signed integer in the radix specified by the second argument.

In the next step this parsed value is then passed as an argument to Integer.toBinaryString() method. This method returns the string representation of the unsigned integer value represented by the argument in binary (base 2).

Finally print the binary value on console. Here’s the program to convert hexadecimal to binary.

import java.util.Scanner;
public class HexadecimalToBinaryJava 
{
   public static void main(String[] args)
   {
      int number;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a number to convert hexadecimal to binary: ");
      number = Integer.parseInt(sc.nextLine(), 16);
      String strBinary = Integer.toBinaryString(number);
      System.out.println("Binary value is: " + strBinary);
      sc.close();
   }
}


Output:

Please enter a number to convert hexadecimal to binary: DEAB
Binary value is: 1101111010101011

Please enter a number to convert hexadecimal to binary: abcd
Binary value is: 1010101111001101


Also read – polymorphism in java