Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to convert number from decimal to hexa-decimal and vice-versa.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to convert number from decimal to hexa-decimal and vice-versa.

Objective

Write a Java program to convert a Decimal number to Hexadecimal and vice-versa.

Algorithm / Approach

  1. To convert Dec to Hex: Read a decimal string, parse it to an int, and use String.format("%X", deci) to output the Hex equivalent.
  2. To convert Hex to Dec: Read a Hex string, and use Integer.valueOf(hex, 16) to parse it back into a base-10 integer.
Test.java
import java.util.*;
class Test {
 public static void main(String [] ar){
   Scanner sc = new Scanner(System.in);
   System.out.print("Value in Dec:");
   String dec = sc.nextLine();
   int deci = Integer.parseInt(dec);
   String dectohex; 
   dectohex = String.format("%X",deci);
   System.out.println("Hex : "+dectohex);
   System.out.println("---------");
   System.out.print("Value in Hex:");
   String hex = sc.nextLine();
   int hextodec = Integer.valueOf(hex,16);
   System.out.println("Dec : "+hextodec);
 }
}

Expected Output

Value in Dec:106
Hex : 6A
-------------
Value in Hex:6B
Dec : 107

Explanation of the Program

  • Hexadecimal is a base-16 number system (using 0-9 and A-F).
  • Java's Integer wrapper class provides built-in methods to parse strings of different mathematical bases (radix). By passing 16 as the second argument to valueOf, we tell Java to interpret the letters as math values.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT