Java Code Example: convert decimal to hexadecimal number

The ConvertToHex class contains a program that converts an integer value entered by the user into its equivalent hexadecimal value. Here is a detailed explanation of the code:

  1. Import the Scanner class from the java.util package to allow user input from the keyboard.
  2. The class ConvertToHex has a main method where the program logic is defined.
  3. Declare an integer num to store the number entered by the user.
  4. Create a Scanner object s to obtain input from the keyboard using the System.in stream.
  5. Prompt the user to enter a number using the System.out.print method.
  6. Use the nextInt() method of the Scanner class to store the user’s input in the num variable.
  7. Close the Scanner object to free up system resources.
  8. Use the toHexString method of the Integer class to convert the num value into its hexadecimal representation, which is stored in the hex string.
  9. Use the System.out.println method to print the result on the console. The result consists of the message “Hexadecimal value of number ” followed by the decimal value of num, followed by the message ” is: ” followed by the hexadecimal value stored in the hex string.
import java.util.Scanner;

public class ConvertToHex {
  public static void main(String[] args) {
    int num;

    Scanner s = new Scanner(System.in);
    System.out.print("Please enter a number: ");

    num = s.nextInt();

    s.close();

    String hex = Integer.toHexString(num);
    System.out.println("Hexadecimal value of number " + num + " is: " + hex);
  }
}
Output
Please enter a number: 14
Hexadecimal value of number 14 is: e