Java program to convert a decimal number to Hexadecimal :
In this tutorial, I will show you how to convert a decimal number to Hexadecimal in Java using two different methods.
To convert a number from decimal to Hexadecimal :
- 
Get the number from the user using Scanner
 - 
Pass it to a different method to find out the hexadecimal
 - 
First get the reminder dividing the number by 16
 - 
If it is less than 10, add it to a result string. The result string should be empty at first. We will keep updating the result each time.
 - 
If the remainder is greater than or equal to 10, add to the result string_ ‘A’,‘B’,‘C’,‘D’,‘E’ or ‘F’ for 10,11,12,13,14 and 15_ respectively.
 - 
Now, change the number to_ number/16_
 - 
Iterate it till the number is greater than 0
 
Example Program :
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringJoiner;
public class Test {
    static char hexaChar[] = {'F','E','D','C','B','A'};
    static String findHexa(int no){
        String result =""; //variable to store final result
        int reminder ; //variable to store reminder
        while(no>0){
            reminder = no % 16;
            if(reminder > 9){
                result = hexaChar[15 - reminder] + result;
            }else{
                result = reminder+result;
            }
            no = no/16;
        }
    return result;
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number ");
        int num = scanner.nextInt();
        System.out.println("Hexa "+findHexa(num));
    }
}
Output :
Enter a number 
1234
Hexa 4D2
Enter a number 
12365
Hexa 304D
We can also use public static String toHexString(int i) method of _Integer _class to convert a number to Hexadecimal directly in Java. Program :
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number ");
        int num = scanner.nextInt();
        System.out.println("Hexa "+Integer.toHexString(num));
    }
}
The output is same as the first example.
