Java Program to Convert Decimal to Hexadecimal Using Recursion

You are currently viewing Java Program to Convert Decimal to Hexadecimal Using Recursion

Java program to convert decimal to hexadecimal using recursion

// Java program to convert decimal to hexadecimal 
// using the recursion

import java.util.*;

public class Main {
  static char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
  
  static String strHex = "";
  static int num = 0;

  public static String decToHex(int dec) {
    if (dec != 0) {
      num = dec % 16;
      strHex = hexChar[num] + strHex;
      dec = dec / 16;
      decToHex(dec);
    }
    return strHex;
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);

    int num = 0;
    String res;

    System.out.printf("Enter number: ");
    num = X.nextInt();

    res = decToHex(num);
    System.out.printf("Hex-Decimal number is: " + res);
  }
}

Output

Enter number: 234
Hex-Decimal number is: EA

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply