Write a program to convert Decimal to Hexadecimal number system


The program starts by importing the Scanner class from the java.util package, which allows user input to be read from the console. Then a class named Decimal_Hexa is defined, which contains the main method that executes the program.

Inside the main method, the program prompts the user to enter a decimal number using System.out.print and reads the input value using the Scanner class.

After that, the program declares and initializes variables to be used in the conversion process. The rem variable stores the remainder of the division of the decimal number by 16. The str variable is an empty string that will store the hexadecimal representation of the decimal number. The hex array stores the hexadecimal digits in order.

The program then enters a while loop that runs as long as the decimal number is greater than 0. Inside the loop, the program calculates the remainder of the division of the decimal number by 16 and appends the corresponding hexadecimal digit to the front of the str string. The decimal number is then divided by 16 to move to the next digit.

After the loop completes, the str string contains the hexadecimal representation of the decimal number. This value is printed to the console using System.out.println.

Source Code

/*import java.util.Scanner;
class Decimal_Hexa
{
    public static void main(String args[])
    {
      Scanner input = new Scanner( System.in );
      System.out.print("Enter a Decimal Number : ");
      int num =input.nextInt();
      String str = Integer.toHexString(num);
      System.out.println("Decimal to Hexadecimal: "+str);
    }
}
*/
import java.util.Scanner;
class Decimal_Hexa
{
   public static void main(String args[])
   {
     Scanner input = new Scanner( System.in );
     System.out.print("Enter a Decimal Number : ");
     int dec =input.nextInt();
     int rem;
     String str=""; 
     char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
 
     while(dec>0)
     {
       rem=dec%16; 
       str=hex[rem]+str; 
       dec=dec/16;
     }
     System.out.println("Decimal to Hexadecimal: "+str);
  }
}

Output

Enter a Decimal Number : 123
Decimal to Hexadecimal: 7B

Example Programs