Java Program to convert decimal to hexadecimal

Here we are explaining how to write a java program to convert decimal numbers to hexadecimal numbers.

What is the difference between decimal numbers and hexadecimal numbers?

A decimal number is a base-ten number. The hexaDecimal number is the base sixteen number system. It includes the 0 to 9 and A to F.

Examples of decimal number: 100,200,500.23

Examples of hexadecimal numbers: 7A,5,8B.


How to implement the java program to convert decimal numbers to hexadecimal numbers in java?

First, we have to declare the class DecToHex.Declare the integer variable r to hold the remainder and hex to hold the hexadecimal number. Initialize a character array hex_string. Create an object of the scanner class as sc. Read the decimal number from the user into the variable dec. Then by using while loop checks if dec>0 if true then calculate the remainder r as dec mod 16.Then hex=hex_string[r]+hex,dec=dec/16.Display the hexadecimal number as hex.



STEP 1: Declare the class DecToHex with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3:Declare the integer variable r, string variable hex.

STEP 4:Declare the character array hex_string.

STEP 5: Create an object of the scanner class as sc.

STEP 6: Read the decimal number from the user into the variable dec.

STEP 7: By using while loop checks if dec>0, if true then do step 8.

STEP 8: r=dec,hex=hex_string[r]+hex,dec=dec/16.

STEP 9: Display Hexadecimal number as hex.


Java Source Code

                                          import java.util.Scanner;
public class DecToHex
   public static void main(String args[])
       int r;
       String hex="";
       char hex_string[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
     Scanner sc = new Scanner( );
     System.out.println("Enter the decimal number : ");
     int dec =sc.nextInt();
     System.out.println("Hexadecimal Number is: "+hex);


Enter the decimal number :
Hexadecimal Number is: 3E8